Compare commits

...

1055 Commits

Author SHA1 Message Date
link2xt
c59f21230d chore(release): prepare for 1.132.1 2023-12-12 02:58:29 +00:00
link2xt
828cc1fbd1 fix(connectivity): return false from all_work_done() immediately after connecting
We do not want all_work_done() to return true immediately
after calling start_io(), but only when connection goes idle.

"Connected" state is set immediately after connecting to the server,
but it does not mean there is nothing to do.

This change make all_work_done() return false
from the Connected state and introduces a new Idle
connectivity state that is only set before connection
actually goes idle. For idle state all_work_done() returns true.

From the user point of view both old Connected state
and new Idle state look the same.
2023-12-12 02:19:51 +00:00
link2xt
57f4958fc6 test(deltachat-rpc-client): test Account.{import,export}_self_keys 2023-12-11 06:43:10 +00:00
link2xt
3aeb57b4df api(deltachat-jsonrpc-client): add Account.{import,export}_self_keys 2023-12-11 06:43:10 +00:00
link2xt
1b85614db9 fix: renew IDLE timeout on keepalives and reduce it to 5 minutes
This change depends on async-imap update that resets the timeout
every time an `* OK Still here` is received.

Reducing timeout allows to detect lost connections
not later than 6 minutes
because Delta Chat will attempt to finish IDLE with DONE
after 5 minutes without keepalives
and will either get TCP RST directly
or, worst case, wait another minute for TCP socket read timeout.
2023-12-11 06:32:13 +00:00
link2xt
57ecf49eb1 chore: fix typo ("Bot" instead of "Bob") 2023-12-11 04:08:45 +00:00
iequidoo
f279b0d1e5 feat: Sync user actions for ad-hoc groups across devices (#5065)
Ad-hoc groups don't have grpid-s that can be used to identify them across devices and thus wasn't
synced until now.

The same problem already exists for assigning messages to ad-hoc groups and this assignment is done
by `get_parent_message()` and `lookup_chat_by_reply()`. Let's reuse this logic for the
synchronisation, it works well enough and this way we have less surprises than if we try to
implement grpids for ad-hoc groups. I.e. add an `Msgids` variant to `chat::SyncId` analogous to the
"References" header in messages and put two following Message-IDs to a sync message:
- The latest message A having `DownloadState::Done` and the state to be one of `InFresh, InNoticed,
  InSeen, OutDelivered, OutMdnRcvd`.
- The message that A references in `In-Reply-To`.

This way the logic is almost the same to what we have in `Chat::prepare_msg_raw()` (the difference
is that we don't use the oldest Message-ID) and it's easier to reuse the existing code.

NOTE: If a chat has only an OutPending message f.e., the synchronisation wouldn't work, but trying
to work in such a corner case has no significant value and isn't worth complicating the code.
2023-12-09 01:41:07 -03:00
iequidoo
32071297e6 feat: Add "From:" to protected headers for signed-only messages 2023-12-09 00:57:35 -03:00
link2xt
1d98c38ff3 ci: update to Rust 1.74.1 2023-12-08 23:52:36 +00:00
link2xt
c09e0e2b65 refactor: move AEAP and peerstate save from mimeparser to receive_imf()
Ideally mimeparser should be functional
and have no side effects such as modifying a peerstate in the database.
2023-12-08 23:32:03 +00:00
link2xt
0c8f967391 test: refine test_encrypted_no_autocrypt()
- Use TestContextManager
- Actually run receive_imf rather than only mimeparser on "received" messages
- Check that received message parts actually have a padlock
2023-12-08 23:32:03 +00:00
link2xt
aca34379e0 fix: add padlock to empty part if the whole message is empty
parse_mime_recursive() skips empty text parts,
so there may be no parts as the result of parsing.
In this case an empty part is added.
However, because it is added with parts.push()
rather than add_single_part(),
it is added without a padlock even if the message is encrypted.
`do_add_single_part()` adds padlock (GuaranteeE2EE param)
and should be used to add parts instead.
2023-12-07 03:38:20 +00:00
link2xt
1edd7045be chore(release): prepare for 1.132.0 2023-12-06 17:52:46 +00:00
B. Petersen
c784c499c2 fix: do not check lock_task on iOS before syncing
`lock_task` is anyways always `None` on iOS
to avoid lock files held open and cause 0xdead10cc crashes.
2023-12-06 18:17:49 +01:00
link2xt
36c751bcc3 chore: cargo update 2023-12-06 17:02:22 +00:00
link2xt
8a14a84bec test: check that ac2 gets a verified chat in test_securejoin_after_contact_resetup 2023-12-06 16:44:18 +00:00
link2xt
b00703cec2 fix: protect groups even if some members are not verified 2023-12-06 16:44:18 +00:00
link2xt
05e783564f refactor: log if the group is created as protected or not 2023-12-06 16:44:18 +00:00
link2xt
330fb02486 test: add test_securejoin_after_contact_resetup test
This test reproduces a bug preventing joining the group with a QR code
if the group already has a contact with inconsistent key state,
which means both Autocrypt and verified key exist,
but don't match.
This can happen when an invite QR code created by this contact
is scanned as scanning an invite code creates unprotected group
with the inviter for info messages.
If securejoin process never finishes because the inviter is offline,
group remains in this unprotected state with added inviter.

Normally the group becomes verified when a "Member added" (vg-member-added)
message is received in the chat.
However, current code checks that all members
of the chat are verified
(have a green checkmark, use verified key in 1:1 chat)
before marking the group as verified and fails otherwise.
2023-12-06 16:44:18 +00:00
link2xt
1447ab8dac refactor: clean up the logs and reduce noise
- Remove "Detected Autocrypt-mime message" logs printed for every incoming Autocrypt message.
- Print only a single line at the beginning of receive_imf with both the Message-ID and seen flag.
- Print Securejoin step only once, inside handle_securejoin_handshake or observe_securejoin_on_other_device.
- Do not log "Not creating ad-hoc group" every time ad-hoc group is not created, log when it is created instead.
- Log ID of the chat where Autocrypt-Gossip for all members is received.
- Do not print "Secure-join requested." for {vg,vc}-request, we already log the step.
- Remove ">>>>>>>>>>>>>>>>>>>>>>>>>" noise from securejoin logs.
2023-12-06 01:56:35 +00:00
link2xt
d574ee4edb chore: update zerocopy from 0.7.28 to 0.7.29
0.7.28 is yanked.
2023-12-05 19:25:27 +00:00
link2xt
814fe953a9 chore(cargo): update filetime 2023-12-05 16:45:24 +00:00
link2xt
280f13b8cf fix: do not lock accounts.toml on iOS
This results in 0xdead10cc crashes on suspend.
iOS itself ensures that multiple instances of Delta Chat are not running.
2023-12-04 21:51:17 +00:00
link2xt
a96b44a482 fix: do not mark recipients as verified if there is no Chat-Verified header 2023-12-04 15:34:09 +00:00
link2xt
4286d248e9 feat: increase TCP timeouts from 30 to 60 seconds
GitHub Action tests sometimes fail with TCP connection
timeouts, especially for macOS.
2023-12-04 12:50:07 +00:00
dependabot[bot]
116537019b chore(deps): bump self_cell from 1.0.1 to 1.0.2 in /fuzz
Bumps [self_cell](https://github.com/Voultapher/self_cell) from 1.0.1 to 1.0.2.
- [Release notes](https://github.com/Voultapher/self_cell/releases)
- [Commits](https://github.com/Voultapher/self_cell/compare/v1.0.1...v1.0.2)

---
updated-dependencies:
- dependency-name: self_cell
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-03 16:05:27 -03:00
iequidoo
8b37b8c1fd fix: Don't sort message creating a protected group over a protection message (#4963)
Otherwise it looks like the message creating a protected group is not verified. For this, use
`sent_timestamp` of the received message as an upper limit of the sort timestamp (`msgs.timestamp`)
of the protection message. As the protection message is added to the chat earlier, this way its
timestamp is always less or eq than the received message's timestamp.
2023-12-03 15:10:54 -03:00
iequidoo
63b4339ca0 test: Message order in a just created protected group on the second device (#4963)
Test that on the second device of a protected group creator the first message is
`SystemMessage::ChatProtectionEnabled` and the second one is the message populating the group.
2023-12-03 15:10:54 -03:00
link2xt
fdd239f61f fix: narrow the scope of verification exception to 1:1 chats
Allowing outgoing unencrypted messages in groups with 2 members
breaks the test
`python/tests/test_0_complex_or_slow.py::test_verified_group_vs_delete_server_after`
2023-12-03 15:46:56 +00:00
link2xt
5ca5d95c5e refactor: call has_verified_encryption() in a single place
This centralizes all Securejoin/verification checks and updates in one
place right before add_parts() even before we assign the message to
the chat, so we can decouple chat logic from verification logic.
2023-12-03 15:46:56 +00:00
link2xt
3fcad50924 refactor: move to_ids.is_empty() check into mark_recepients_as_verified() 2023-12-03 15:46:56 +00:00
link2xt
8e40540d24 refactor: add debug assertion where we expect a 1:1 chat 2023-12-03 15:46:56 +00:00
link2xt
04d22bb84d refactor: remove chattype argument from has_verified_encryption() 2023-12-03 15:46:56 +00:00
link2xt
5415f1bfa1 docs: has_verified_encryption() does not check that all members are verified 2023-12-03 15:46:56 +00:00
link2xt
ff3bf4791a chore: update dependencies 2023-12-03 00:43:21 +00:00
dependabot[bot]
eebea216cb chore(cargo): bump testdir from 0.8.1 to 0.9.0
Bumps [testdir](https://github.com/flub/testdir) from 0.8.1 to 0.9.0.
- [Changelog](https://github.com/flub/testdir/blob/main/CHANGELOG.md)
- [Commits](https://github.com/flub/testdir/compare/v0.8.1...v0.9.0)

---
updated-dependencies:
- dependency-name: testdir
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-02 15:50:51 +00:00
link2xt
fbcd7f46b8 chore(release): prepare for 1.131.9 2023-12-02 01:18:34 +00:00
iequidoo
846278b18e feat: chat::rename_ex: Don't send sync message if usual message is sent
It's not necessary and in other places like add_contact_to_chat_ex() sync messages are also sent
only if there are no system messages sent like MemberAddedToGroup.
2023-12-01 21:41:58 -03:00
iequidoo
2f2b1e18bf test: Split test_sync_alter_chat() into smaller tests 2023-12-01 21:41:58 -03:00
iequidoo
073c250fa4 refactor: Add test_utils::sync()
Add a function that pops a sync message from one Alice's device and receives it on another.
2023-12-01 21:41:58 -03:00
iequidoo
1f336f89a6 feat: Sync Config::Displayname across devices (#4893)
We already synchronise status/footer when we see a self-sent message with a Chat-Version
header. Would be nice to do the same for display name.

But let's do it the same way as for `Config::{MdnsEnabled,ShowEmails}`. Otherwise, if we sync the
display name using the "From" header, smth like `Param::StatusTimestamp` is needed then to reject
outdated display names. Also this timestamp needs to be updated when `Config::Displayname` is set
locally. Also this wouldn't work if system time isn't synchronised on devices. Also using multiple
approaches to sync different config values would lead to more code and bugs while having almost no
value -- using "From" only saves some bytes and allows to sync some things w/o the synchronisation
itself to be enabled. But the latter also can be a downside -- if it's usual synchonisation, you can
(potentially) disable it and share the same email account across people in some organisation
allowing them to have different display names. With using "From" for synchronisation such a
capability definitely requires a new config option.
2023-12-01 21:41:58 -03:00
iequidoo
a47fec7f6c feat: Sync Config::{MdnsEnabled,ShowEmails} across devices (#4954)
Motivation: Syncing these options will improve UX in very most cases and should be done. Other
candidates are less clear or are advanced options, we can reconsider that at some point later.

Approach:
- Sync options one-by-one when the corresponding option is set (even if to the same value).
- Don't sync when an option is reset to a default as defaults may differ across client versions.
- Check on both sides that the option should be synced so that if there are different client
  versions, the synchronisation of the option is either done or not done in both directions.
  Moreover, receivers of a config value need to check if a key can be synced because some settings
  (e.g. Avatar path) could otherwise lead to exfiltration of files from a receiver's device if we
  assume an attacker to have control of a device in a multi-device setting or if multiple users are
  sharing an account.
- Don't sync `SyncMsgs` itself.
2023-12-01 21:41:58 -03:00
iequidoo
084434d3b4 feat: receive_imf_inner: Add missing initialisation of ReceivedMsg::from_is_signed 2023-12-01 21:41:58 -03:00
iequidoo
ebfbc11973 feat: Don't affect MimeMessage with "From" and secured headers from encrypted unsigned messages
If a message is encrypted, but unsigned:
- Don't set `MimeMessage::from_is_signed`.
- Remove "secure-join-fingerprint" and "chat-verified" headers from `MimeMessage`.
- Minor: Preserve "Subject" from the unencrypted top level if there's no "Subject" in the encrypted
  part, this message is displayed w/o a padlock anyway.

Apparently it didn't lead to any vulnerabilities because there are checks for
`MimeMessage::signatures.is_empty()` in all necessary places, but still the code looked dangerous,
especially because `from_is_singed` var name didn't correspond to its actual value (it was rather
`from_is_encrypted_maybe_signed`).
2023-12-01 19:06:11 -03:00
link2xt
9cc9579b2d feat: remove receiver limit on .xdc size
If we have downloaded the file anyway,
might as well allow to open it.
2023-12-01 15:53:38 +00:00
link2xt
7beccd9dbc refactor: better error context in send_webxdc_status_update_struct() 2023-12-01 15:19:23 +00:00
link2xt
0e195bc7a2 fix: lock the database when INSERTing a webxdc update
`query_row_optional` does not hold the write lock
and may fail with "database is locked" error
or cause the other task such as SMTP loop to fail.
2023-12-01 15:19:23 +00:00
link2xt
f89efd5fce test: test inserting lots of webxdc updates
Currently this leads to
DEBUG    root:rpc.py:136 account_id=1 got an event {'kind': 'Warning', 'msg': 'src/scheduler.rs:711: send_smtp_messages failed: failed to send message: failed to update retries count: database is locked: Error code 5: The database file is locked'}
and
FAILED tests/test_webxdc.py::test_webxdc_insert_lots_of_updates - deltachat_rpc_client.rpc.JsonRpcError: {'code': -1, 'message': 'database is locked\n\nCaused by:\n    Error code 5: The database file is locked'}
2023-12-01 15:19:23 +00:00
link2xt
48d278fca9 chore: update dependencies 2023-12-01 02:41:48 +00:00
link2xt
c84effdaa1 refactor: add more error context to send_webxdc_status_update()
This is a follow-up to b9fa05c3bb
2023-12-01 02:32:21 +00:00
link2xt
e9601ef138 test: make Result-returning tests produce a line number
Without this change
when the test returns a `Result`, `cargo test` does not show
the line number.

To make the tests as easy to debug as the panicking tests,
enable `backtrace` feature on `anyhow` and add debug information
to add source line numbers to backtraces.

Now running `RUST_BACKTRACE=1 cargo test` produces backtraces
with the line numbers. For example:

Error: near ",": syntax error in SELECT COUNT(,,*) FROM msgs_status_updates; at offset 13

Caused by:
    Error code 1: SQL error or missing database

Stack backtrace:
   0: <core::result::Result<T,F> as core::ops::try_trait::FromResidual<core::result::Result<core::convert::Infallible,E>>>::from_residual
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library/core/src/result.rs:1962:27
   1: deltachat::sql::Sql::query_row::{{closure}}::{{closure}}
             at ./src/sql.rs:466:23
   2: deltachat::sql::Sql::call::{{closure}}::{{closure}}
             at ./src/sql.rs:379:55
   3: tokio::runtime::context::runtime_mt::exit_runtime
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/context/runtime_mt.rs:35:5
   4: tokio::runtime::scheduler::multi_thread::worker::block_in_place
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/scheduler/multi_thread/worker.rs:438:9
   5: tokio::runtime::scheduler::block_in_place::block_in_place
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/scheduler/block_in_place.rs:20:5
   6: tokio::task::blocking::block_in_place
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/task/blocking.rs:78:9
   7: deltachat::sql::Sql::call::{{closure}}
             at ./src/sql.rs:379:19
   8: deltachat::sql::Sql::query_row::{{closure}}
             at ./src/sql.rs:469:10
   9: deltachat::sql::Sql::count::{{closure}}
             at ./src/sql.rs:443:76
  10: deltachat::webxdc::tests::change_logging_webxdc::{{closure}}
             at ./src/webxdc.rs:2644:18
  11: <core::pin::Pin<P> as core::future::future::Future>::poll
             at /rustc/79e9716c980570bfd1f666e3b16ac583f0168962/library/core/src/future/future.rs:125:9
  12: tokio::runtime::park::CachedParkThread::block_on::{{closure}}
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/park.rs:282:63
  13: tokio::runtime::coop::with_budget
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/coop.rs:107:5
      tokio::runtime::coop::budget
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/coop.rs:73:5
      tokio::runtime::park::CachedParkThread::block_on
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/park.rs:282:31
  14: tokio::runtime::context::blocking::BlockingRegionGuard::block_on
             at /home/user/.cargo/registry/src/index.crates.io-6f17d22bba15001f/tokio-1.34.0/src/runtime/context/blocking.rs:66:9
...

Line 10 of the backtrace contains the line number in the test (2644).
2023-11-30 22:27:38 +00:00
iequidoo
44c5cd5526 feat: Ratelimit IMAP connections (#4940)
Limit the number of IMAP connections to 1 per minute regardless of the reason of reconnection, but
allow one immediate retry. This is more reliable than ratelimiting only in error conditions because
ratelimiting can't be skipped by mistake. Anyway connections shouldn't be frequent in normal
operation mode.
2023-11-30 19:22:01 -03:00
link2xt
1c9662a8f2 refactor: rename min_verified into verified 2023-11-30 12:04:03 +00:00
link2xt
5d08b2ce33 refactor: remove unused PeerstateVerifiedStatus 2023-11-30 12:04:03 +00:00
link2xt
bb9d7d7ef3 feat: send Chat-Verified headers in 1:1 chats
Chat-Verified is going to be useful to upgrade one-way verification
to bidirectional verification.
2023-11-30 12:04:03 +00:00
link2xt
766bb5c8aa refactor: factor securejoin processing out of add_parts 2023-11-30 12:04:03 +00:00
link2xt
84144659cf refactor: remove {vc-contact-confirm,vg-member-added}-received steps 2023-11-30 12:04:03 +00:00
link2xt
1394137436 refactor: make min_verified a boolean
We either need a securejoin or autocrypt key,
there are no intermediate states.
2023-11-30 12:04:03 +00:00
link2xt
998614b923 api: make Contact.is_verified() return bool 2023-11-30 12:04:03 +00:00
B. Petersen
5b346397b8 api: deprecate CFFI APIs dc_send_reaction(), dc_get_msg_reactions(), dc_reactions_get_contacts(), dc_reactions_get_by_contact_id(), dc_reactions_unref and dc_reactions_t
this is now done with jsonrpc via
`dc_jsonrpc_request()` or `dc_jsonrpc_blocking_call()`
using the methods `send_reaction` and `get_message_reactions`
2023-11-29 11:29:29 +01:00
B. Petersen
1f99269002 api: remove dc_get_http_response(), dc_http_response_get_mimetype(), dc_http_response_get_encoding(), dc_http_response_get_blob(), dc_http_response_get_size(), dc_http_response_unref() and dc_http_response_t from cffi
this is now done with jsonrpc via
`dc_jsonrpc_request()` or `dc_jsonrpc_blocking_call()`
using the method `get_http_response`
2023-11-29 11:29:29 +01:00
iequidoo
160cbe8125 fix: Use keyring with all private keys when decrypting a message (#5046)
Before a keyring with the only default key was used, i.e. the key used for signing and encrypting to
self.
2023-11-29 02:20:19 -03:00
link2xt
b9fa05c3bb refactor: improve logging of send_webxdc_status_update errors
send_webxdc_status_update JSON-RPC call
and corresponding Rust call sometimes fail in CI with
---
database is locked

Caused by:
    Error code 5: The database file is locked
---

Adding more context to send_webxdc_status_update() errors
to better localize the error origin.
2023-11-28 22:48:55 +00:00
link2xt
4287a4d3ad refactor: factor out insert_tombstone 2023-11-28 21:57:41 +00:00
link2xt
37d2aafb26 fix: return correct MsgId for malformed message tombstone
.execute() returns the number of affected rows,
in this case it is always 1 and MsgId(1) is returned
instead of the actual tombstone row ID.
2023-11-28 21:57:41 +00:00
link2xt
4332170691 ci: add exception for RUSTSEC-2023-0071 to cargo-deny config
See
<https://rustsec.org/advisories/RUSTSEC-2023-0071>
and discussion at
<https://github.com/RustCrypto/RSA/issues/19>
for details.
2023-11-28 16:26:11 +00:00
link2xt
9a7c0f4737 chore: update OpenSSL 2023-11-28 15:05:34 +00:00
link2xt
9e7e172a7b build: switch from fork of iroh to iroh 0.4.2 pre-release 2023-11-28 02:59:42 +00:00
link2xt
71fbaf572a chore(release): prepare for 1.131.8 2023-11-28 00:01:17 +00:00
link2xt
2ab29e5bfa fix: allow IMAP servers not returning UIDNEXT on SELECT and STATUS 2023-11-27 23:50:43 +00:00
link2xt
85f8f910b9 chore: update wasm-bindgen from 0.2.88 to 0.2.89
0.2.88 is yanked: https://github.com/rustwasm/wasm-bindgen/issues/3685
2023-11-27 21:41:23 +00:00
link2xt
b779d08d7f test: check that receive_status_update has forward compatibility
This ensures old version of Delta Chat will be fine with a new "uid" field.
2023-11-27 13:49:41 +00:00
link2xt
3b5634f14b fix: do not emit events about webxdc update events logged into debug log webxdc 2023-11-27 13:49:41 +00:00
link2xt
f91ba357cf feat(webxdc): add unique IDs to status updates sent outside
This allows for deduplication
if status updates are sent over multiple transports.
2023-11-27 13:49:41 +00:00
Hocuri
616faff96b fix: Use the correct securejoin strings used in the UI, remove old TODO (#5047) 2023-11-26 15:54:11 +01:00
link2xt
5e6869403e chore(release): prepare for 1.131.7 2023-11-24 18:26:25 +00:00
link2xt
7ff7d82959 Revert "fix: check UIDNEXT with a STATUS command before going IDLE"
This reverts commit 2e50abedaa.

STATUS is broken on mail.163.com.
It returns `STATUS "INBOX" ()` reply
when `STATUS "INBOX" (UIDNEXT)` is requested.
2023-11-24 18:19:02 +00:00
link2xt
9b751c1865 chore(release): prepare for 1.131.6 2023-11-21 21:05:29 +00:00
link2xt
d1d31096e0 fix: fail fast if IMAP FETCH cannot be parsed
Otherwise when connection is lost IMAP may get into infinite loop
trying to parse remaining bytes:
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.
11-21 18:00:48.442 14858 12946 W DeltaChat: src/imap.rs:1457: Failed to process IMAP FETCH result: io: bytes remaining in stream.

Returning an error bubbles it up to `fetch_idle()`
which will call `trigger_reconnect()` and drop the connection.
2023-11-21 20:59:16 +00:00
link2xt
30f8522626 docs: generate deltachat-rpc-client documentation
To preview the docs, run:
```
scripts/build-python-docs.sh
firefox dist/html/index.html
```

I have removed the Makefile because modern Sphinx Makefile is just a
wrapper for `sphinx-build -M`:
3596590317/sphinx/templates/quickstart/Makefile.new_t
and sphinx-quickstart even has an option `--no-makefile`.
`make.bat` makes even less sense.
In `scripts/build-python-docs.sh` I use `sphinx-build` directly
without `make` wrapper.
2023-11-20 19:56:22 +00:00
link2xt
d3c221e061 chore: update dependencies 2023-11-20 19:52:40 +00:00
link2xt
8a421224f8 chore(release): prepare for 1.131.5 2023-11-20 19:04:57 +00:00
link2xt
7dfce71ac9 fix: lowercase addr when it is set
Prevent users from creating new accounts with uppercase letters
in the address.
2023-11-20 16:46:59 +00:00
link2xt
35ba97f76a fix: lowercase the address in member added/removed messages 2023-11-20 16:46:59 +00:00
link2xt
41921eaf3d fix: compare verifier addr to peerstate addr with addr_cmp 2023-11-20 16:46:59 +00:00
link2xt
03221ea86c refactor: lowercase the address in addr_normalize() 2023-11-20 16:46:59 +00:00
link2xt
b50761e4d1 api: turn ContactAddress into an owned type
This allows to normalize the address on creation more,
e.g. lowercase it.
2023-11-20 16:46:59 +00:00
link2xt
40dea771cc ci: test with Rust 1.74 2023-11-19 21:41:28 +00:00
link2xt
e011f8f42f chore: fix Rust 1.74 clippy warning 2023-11-19 21:40:19 +00:00
link2xt
09d4b4354a feat: lowercase addresses in Autocrypt and Autocrypt-Gossip
Email addresses should generally be compared case-insensitively,
but there may be errors in comparison code.
To reduce the chance of problems, encode addresses
in Autocrypt and Autocrypt-Gossip in lowercase
to avoid propagating uppercase characters over the network
to other accounts potentially running buggy code.
2023-11-19 06:22:25 +00:00
link2xt
ab151654fb chore: remove unused import from python tests 2023-11-18 11:32:34 +01:00
link2xt
ea9556b1b9 test: port test_aeap_flow_verified to JSON-RPC 2023-11-18 11:32:34 +01:00
link2xt
3dc6fd5c10 api(deltachat-rpc-client): add Message.get_sender_contact() 2023-11-18 11:32:34 +01:00
link2xt
f39acbc037 test: port test_qr_new_group_unblocked() to JSON-RPC 2023-11-18 11:32:34 +01:00
link2xt
005f7ff07e test: port test_qr_join_chat_with_pending_bobstate_issue4894 to JSON-RPC 2023-11-18 11:32:34 +01:00
link2xt
144ca7c171 test: port test_qr_join_chat to JSON-RPC
Disabled `verified_one_on_one_chats` is not tested
as it is not interesting, other checks are moved.
2023-11-18 11:32:34 +01:00
link2xt
7012b99d73 test: remove test_qr_setup_contact from online python tests
There is an identical `test_qr_setup_contact` in deltachat-rpc-client
test suite which also checks that contact profiles get verified.
2023-11-18 11:32:34 +01:00
Hocuri
72bacd56f7 Update securejoin links 2023-11-18 11:30:59 +01:00
iequidoo
cc75038ccc docs: Contributing guidelines for error handling 2023-11-18 00:34:47 -03:00
link2xt
f4810125e3 fix: recognize Chat-Group-Member-Added of self case-insensitively
If configured address is `Bob@example.net`,
but the message arrives adding `bob@example.net`,
Bob's device should still recognize it as addition of self
and fully recreate the group.
2023-11-18 02:42:28 +00:00
link2xt
acf1faf151 refactor(deltachat-rpc-client): add helper functions to wait for securejoin 2023-11-17 13:32:20 +00:00
link2xt
255fbe94f7 fix: do not use square brackets error for unknown sender
If the sender of the message in protected group chat
is not a member of the chat, mark the sender name with `~`
as we do it in non-protected chats and set the error
instead of replacing the whole message with
"Unknown sender for this chat. See 'info' for more details."

To send a message to a protected group this way
the sender needs to know the group ID
and sign the message with the current verified key.
Usually this is just a late message
delivered shortly after the user has left
the group or was removed from it.

Replacing the message with a single error text part
as done before this change makes it impossible
to access anything other than text, such as attached images.
2023-11-17 10:26:38 +00:00
link2xt
b5d1eba28e docs: add missing 1.131.4 link to the changelog 2023-11-17 10:13:18 +00:00
iequidoo
1509978738 fix: chat::rename_ex(): Sync improved chat name to other devices
Other devices should get the same chat name as the currently used device, i.e. the name a user sees
after renaming the chat. This fix is minor because `improve_single_line_input()` logic isn't going
to change often, but still, and also it simplifies the code.
2023-11-17 03:55:50 -03:00
iequidoo
607b9e55a9 fix: Chat::sync_contacts(): Fetch contact addresses in a single query
In order to protect from races with contacts removal and (just in case) dangling contact ids in
`chats_contacts` table.
2023-11-17 03:55:50 -03:00
holger krekel
7c4c980409 for testrun.org subdomains we can allow 60 messages per minute (or lift the limit completely but maybe good to protect against wild-running bots or so) 2023-11-17 06:50:19 +00:00
B. Petersen
b8ad3ec1b1 chore(release): prepare for 1.131.4 2023-11-16 21:04:19 +01:00
link2xt
87dd33f66e fix: always add "Member added" as system message 2023-11-16 01:54:45 +00:00
link2xt
7d8d13759a docs: document DC_DOWNLOAD_UNDECIPHERABLE
This was introduced in https://github.com/deltachat/deltachat-core-rust/pull/4685
for internal use when looking up a chat based on In-Reply-To,
but actually affects the UIs as they should not display Download button
when the message is downloaded but cannot be decrypted.
2023-11-15 23:07:10 +00:00
link2xt
2b4f2a9171 chore(release): prepare for 1.131.3 2023-11-15 20:08:20 +00:00
link2xt
8e869de350 fix(sync): skip sync when chat name is set to the current one 2023-11-15 19:18:13 +00:00
link2xt
b0ef082b2a fix(sync): ignore unknown sync items to provide forward compatibility 2023-11-15 19:17:38 +00:00
link2xt
bf8e74198d chore: update dependencies 2023-11-15 18:40:15 +00:00
link2xt
e77805471c fix: reset gossiped timestamp on securejoin
If verified key for a contact is changed via securejoin,
gossip the keys in every group with this contact next time
we send a message there to let others learn new verified key
and let the contact who has resetup their device learn keys of others
in groups.
2023-11-15 17:27:37 +00:00
link2xt
45a8004b33 fix: update async-imap to 0.9.4 which does not ignore EOF on FETCH 2023-11-15 15:59:29 +01:00
Simon Laux
990f4dce9b return connectivity html even when IO is stopped.
The returned error is unexpected and no UI I tested with stoped IO really handled it besides maybe displaying a toast.
(desktop and iOS don't handle it, deltatouch shows a toast)

This should not be shown to the user, it is only shown to the user if the UI has a bug, so that bug should be clearly visible.
2023-11-15 13:58:12 +01:00
link2xt
0f36197c54 fix: substitute variables in STATUS error logs 2023-11-15 10:57:05 +00:00
link2xt
890a2bcc15 chore(release): prepare for v1.131.2 2023-11-14 10:13:35 +00:00
link2xt
224355e83a fix: add "setup changed" message for verified key before the message
Merge the code paths for verified and autocrypt key.
If both are changed, only one will be added.

Existing code path adds a message to all chats with the contact
rather than to 1:1 chat. If we later decide that
only 1:1 chat or only verified chats should be notified,
we can add a separate `verified_fingerprint_changed` flag.
2023-11-14 10:00:25 +00:00
link2xt
c6ea4e389a feat: do not post "... verified" messages on QR scan success
We still post "... not verified" on failure.
2023-11-14 09:59:19 +00:00
link2xt
678142b3fb fix: assign MDNs to the trash chat early
Otherwise we will try to create an ad-hoc group
and failing because there are only two contacts
and then unblock a 1:1 chat just to assign
the message to trash in the end.
2023-11-14 08:59:37 +00:00
link2xt
ae6f83cd21 test: add a test checking that read receipt does not unblock 1:1 chat
Hidden 1:1 chat is created for the "chat protected" message.
It should not appear simply because we received
a read receipt from the contact in a group.
2023-11-14 08:59:37 +00:00
link2xt
626b2be1fe api(deltachat-rpc-client): add Account.get_chat_by_contact() 2023-11-14 08:59:37 +00:00
iequidoo
ac5c789c75 feat: Never drop better message from apply_group_changes()
Looks like this doesn't fix anything currently, because a better message from
`apply_group_changes()` doesn't appear in a context with another better message, but why drop it if
it's possible to add it, moreover, messages about implicit member additions are never dropped while
looking less important.
2023-11-14 03:11:30 -03:00
iequidoo
ce2878f1e8 test: If a message implicitly adds a group member, both messages appear (#4987) 2023-11-14 03:11:30 -03:00
link2xt
d4162899b4 fix: ignore special chats when calculating similar chats
The second SQL statement calculating chat size
was already fixed in f656cb29be,
but more important statement calculating member list intersection
was overlooked.
As a result, trash chat with members added there due to former bugs
could still appear in similar chats.
2023-11-13 23:32:52 +00:00
link2xt
e900d50e38 fix: allow to securejoin groups with 1:1 contact request from inviter 2023-11-13 18:24:20 +00:00
link2xt
a438a4746a chore(release): prepare for 1.131.1 2023-11-13 16:14:04 +00:00
link2xt
cfb819506f fix: do not skip actual message parts when group_changes_msg is inserted 2023-11-13 14:18:32 +00:00
link2xt
b86b915f40 chore(release): prepare for 1.131.0 2023-11-13 09:35:57 +00:00
iequidoo
ad5a5ad3db feat: Multi-device broadcast lists (#4953) 2023-11-13 05:00:57 -03:00
iequidoo
74081d8a36 feat: Sync Chat::name across devices (#4953) 2023-11-13 05:00:57 -03:00
iequidoo
34a434f07c refactor: Move chat-related code from sync to chat module
- Reduce cross-module dependencies.
- Stop bloating the `sync` module while implementing synchronisation of more entities.
- Now there's the only `ChatId` :)
2023-11-13 05:00:57 -03:00
iequidoo
dc944d8ca7 test: Broadcast lists synchronisation (#4953) 2023-11-13 05:00:57 -03:00
iequidoo
b06a7e7197 fix: Context::execute_sync_items: Ignore all errors (#4817)
An error while executing an item mustn't prevent next items from being executed. There was a comment
that only critical errors like db write failures must be reported upstack, but in fact it's hard to
achieve in the current design, there are no error codes or so, so it's bug-prone. E.g.
`ChatAction::Block` and `Unblock` already reported all errors upstack. So, let's make error handling
the same as everywhere and just ignore any errors in the item execution loop. In the worst case we
just do more unsuccessful db writes f.e.
2023-11-13 05:00:57 -03:00
iequidoo
fa61d90115 fix: Ignore errors from generating sync messages
It's sufficient if the local state is updated successfully, no need to fail the whole
operation. Anyway delivery of sync messages and applying them on other devices are beyond of our
control. If an error occurs when generating a sync messages, probably a log message is sufficient,
no need to even show it to a user. As for the tests, anyway there are ones on synchronisation which
perform necessary checks. Particularly, some sync messages can't be generated if an account is
unconfigured. Adding the corresponding checks to the device synchronisation code (and maybe even
more checks in the future) would complicate the code unnecessarily. Even errors caused by bugs in
this code aren't a reason to fail a local operation.
2023-11-13 05:00:57 -03:00
iequidoo
7977c9ab44 feat: Sync creating broadcast lists across devices (#4953) 2023-11-13 05:00:57 -03:00
iequidoo
6273a7d54e refactor: Rename Chat::add_sync_item() to sync() 2023-11-13 05:00:57 -03:00
iequidoo
4d1a9c2aa1 feat: Sync chat contacts across devices (#4953)
Sync chat contacts across devices for broadcast lists and groups. This needs the corresponding chat
to exist on other devices which is not the case for unpromoted groups, so it fails for them now but
it's only a warning and will work once creation of unpromoted groups is synchronised too.
2023-11-13 05:00:57 -03:00
Hocuri
b26ded423b Fix #4982: Allow to send unverified securejoin messages to protected chats 2023-11-12 20:15:38 +01:00
Hocuri
e4b6eba5d7 Correct comment 2023-11-12 20:15:38 +01:00
Hocuri
bc225024a1 Add tests 2023-11-12 20:15:38 +01:00
Hocuri
e616ecf160 Fix CI 2023-11-12 20:15:38 +01:00
Hocuri
f93562c6bf Refactorings 2023-11-12 20:15:38 +01:00
Hocuri
ac39c3699b Make sure the resetup happy path works 2023-11-12 20:15:38 +01:00
link2xt
091bc1ab13 fix: encode chat name in the List-ID header
List-ID header is added for broadcast lists.
UTF-8 in email headers is allowed only if
all recipient MTAs support SMTPUTF8 extension,
which is not always the case even if our submission service
reports SMTPUTF8 support.
2023-11-12 19:56:09 +01:00
link2xt
fcbb66a788 chore: update dependencies 2023-11-12 13:35:13 +00:00
link2xt
ab2bc3bfb2 chore: update dependencies 2023-11-10 21:28:28 +00:00
link2xt
42dd6f9d08 chore(release): prepare for 1.130.0 2023-11-10 21:26:27 +00:00
Sebastian Klähn
465bcd46f8 test: test chatlist can load for obfuscated chats (#4979)
close #4598
2023-11-10 20:23:51 +00:00
iequidoo
cc88a6cb58 fix: smtp_loop(): Don't grow timeout if interrupted early (#4833)
Don't grow timeout if interrupted early and slept not enough. Also:
- Don't grow timeout too fast, but 1.5--2 times (randomly) per iteration.
- Don't interrupt if rate-limited.
- Reset timeout if rate-limited. Rate limit isn't an error, so we can start from 30 secs again if an
  error happens then.
2023-11-10 17:17:47 -03:00
iequidoo
ba8f1bfcfd feat: Grow sleep durations on errors in Imap::fake_idle() (#4424) 2023-11-10 17:17:47 -03:00
link2xt
d4d6ced957 fix: do not return hidden chat from dc_get_chat_id_by_contact_id 2023-11-10 20:00:28 +00:00
Hocuri
0b664e75cb docs: mention that people need to set the chatmail server to run the rpc tests 2023-11-10 19:28:29 +00:00
link2xt
1a4c2953f7 refactor: get rid of InterruptInfo
It was passed around, but the boolean inside was not used.
2023-11-10 16:38:01 +00:00
link2xt
765c95de39 refactor(imap): do not check if IDLE is supported twice
We already check if IDLE is supported outside of idle()
2023-11-10 16:38:01 +00:00
link2xt
b2ea8f54df refactor(imap): reduce indentation level in fetch_idle() 2023-11-10 16:38:01 +00:00
link2xt
d7aecabcaa fix: do not apply group changes to special chats
This is a similar check to the one we have in `save_locations`.
2023-11-10 15:46:45 +00:00
holger krekel
9ca049051c fix and streamline a little 2023-11-10 16:46:40 +01:00
Sebastian Klähn
790509676f fix: remove unused --liveconfig option
close  #4892
2023-11-10 16:46:40 +01:00
link2xt
ce016eb567 feat: add secondary verified key
When a key is gossiped for the contact in a verified chat,
it is stored in the secondary verified key slot.

The messages are then encrypted to the secondary verified key
if they are also encrypted to the contact introducing this secondary key.

Chat-Group-Member-Added no longer updates the verified key.
Verified group recovery only relies on the secondary verified key.

When a message is received from a contact
signed with a secondary verified key,
secondary verified key replaces the primary verified key.
When verified key is changed for the contact
in response to receiving a message
signed with a secondary verified key,
"Setup changed" message is added
to the same chat where the message is received.
2023-11-10 15:45:10 +00:00
link2xt
57e34abe98 fix: make UidGrouper robust against duplicate UIDs 2023-11-10 15:42:40 +00:00
link2xt
fd92b7c455 fix: remove Reporting-UA from read receipts
Do not leak Delta Chat core verison to everyone
2023-11-10 15:37:30 +00:00
bjoern
0ee68d1dfc back to two verification-check functions (#4966)
this pr keeps and refines documentation added in #4951, however, reverts
the api introduced by #4951
which turns out to be not useful for UI in practise:

UI anyway check for chat/no-chat beforehand,
so a simple condition in profiles as
`green_checkmark = chat_exist ? chat_is_protected() :
contact_is_verified()`
is more useful in practise and is waht UI need and did already in the
past. (https://github.com/deltachat/deltachat-android/pull/2836 shows a
detailed discussion)

(as a side effect, beside saving code,
this PR saves up to three database calls
(get contact from chat in UI to pass it to profile_is_verified(), get
chat from contact in core, load is_protected in core) - instead, core
can use already is_protected from already loaded chat object)

/me did check rust-tests, fingers crossed for python tests
/me should re-setup python tests on local machine at some point :)
2023-11-09 23:31:18 +01:00
link2xt
1856c622a1 test(deltachat-rpc-client): log all events as debug messages
This is necessary to debug the tests.
2023-11-09 10:06:05 +01:00
link2xt
0a48a2effa refactor: replace inviter_progress macro with a function 2023-11-09 01:58:25 +00:00
link2xt
543864f0f5 test(deltachat-rpc-client): fix securejoin tests
Wait for Bob (joiner) progress 1000
and do not return too early in test_qr_setup_contact().
2023-11-09 01:57:13 +00:00
link2xt
0fe94e47cc test: enable verified 1:1 chats in deltachat-rpc-client tests 2023-11-09 01:57:13 +00:00
link2xt
fc09210aea api: emit JoinerProgress(1000) event when Bob verifies Alice 2023-11-09 01:57:13 +00:00
Hocuri
3e194969c0 fix: Mark 1:1 chat as protected when joining a group 2023-11-09 01:57:13 +00:00
link2xt
391cffb454 docs: add dc_chat_is_protection_broken() to 1.127.0 changelog 2023-11-08 17:53:17 +00:00
Sebastian Klähn
47486f8bab Add Changelog entry for is_protection_broken (#4959)
close #4885
2023-11-08 18:41:55 +01:00
link2xt
620e363ce6 refactor(deltachat-rpc-client): use itertools for thread-safe request ID generation 2023-11-08 17:06:25 +00:00
link2xt
0c2276775d test: test that joining a group verifies Alice and vice versa 2023-11-08 01:56:45 +00:00
iequidoo
ad51a7cd85 feat: apply_group_changes: Add system messages about implicitly added members 2023-11-07 21:09:25 -03:00
B. Petersen
28952789a4 fix: raise lower auto-download limit to 160k 2023-11-07 23:27:02 +00:00
link2xt
14adcdb517 fix: treat reset state as encryption not preferred
This will still degrade 1:1 chats to no encryption,
but will not cause the group to disable encryption
simply because one user got into reset state.
2023-11-07 21:24:23 +00:00
link2xt
cc80590488 test(deltachat-rpc-client): move securejoin tests to a separate file 2023-11-07 18:21:44 +00:00
link2xt
48416289ac api: add dc_contact_is_profile_verified() 2023-11-07 18:14:33 +00:00
link2xt
003a27f625 refactor: hide ChatId::get_for_contact() from public API 2023-11-07 01:19:14 +00:00
bjoern
bff4a2259f chore: update provider-db (#4949) 2023-11-07 01:12:31 +00:00
link2xt
9adf856705 chore: upgrade toml dependency 2023-11-06 22:22:12 +00:00
link2xt
2215de5285 chore(release): prepare for 1.129.1 2023-11-06 20:05:13 +00:00
iequidoo
013467d6c6 test: Group chats device synchronisation 2023-11-06 20:02:28 +00:00
Sebastian Klähn
1f52b8af2f fix: Partial messages do not change group state (#4900)
This message makes that partial messages do not change the group state.
A simple fix and a comprehensive test is added. This is a follow up to
the former #4841 which took a different approach.
2023-11-06 20:01:55 +00:00
iequidoo
ce32f76265 fix: apply_group_changes: Don't implicitly delete members locally, add absent ones instead (#4934)
This is another approach to provide group membership consistency for all members. Considerations:
- Classical MUA users usually don't intend to remove users from an email thread, so if they removed
  a recipient then it was probably by accident.
- DC users could miss new member additions and then better to handle this in the same way as for
  classical MUA messages. Moreover, if we remove a member implicitly, they will never know that and
  continue to think they're still here.

But it shouldn't be a big problem if somebody missed a member removal, because they will likely
recreate the member list from the next received message. The problem occurs only if that "somebody"
managed to reply earlier. Really, it's a problem for big groups with high message rate, but let it
be for now.
2023-11-06 20:00:54 +00:00
link2xt
836f65376c fix(deltachat-rpc-client): add the Lock around request ID
Avoid handing out the same request ID twice.
2023-11-06 20:00:17 +00:00
link2xt
99940dd28c fix: update tokio-imap to fix Outlook STATUS parsing bug 2023-11-06 19:05:36 +00:00
link2xt
ffeb801b58 chore(release): prepare for 1.129.0 2023-11-06 11:07:03 +00:00
link2xt
339bbcf070 chore: update dependencies 2023-11-06 10:53:40 +00:00
link2xt
7b83bddc2d fix(imap): always advance expected UIDNEXT to avoid skipping IDLE in a loop
Ensure the client does not busy loop
skipping IDLE if UIDNEXT of the mailbox is higher than
the last seen UID plus 1, e.g. if the message
with UID=UIDNEXT-1 was deleted before we fetched it.

We do not fallback to UIDNEXT=1 anymore
if the STATUS command cannot determine UIDNEXT.
There are no known IMAP servers with broken STATUS so far.
This allows to guarantee that select_with_uidvalidity()
sets UIDNEXT for the mailbox and use it in fetch_new_messages()
to ensure that UIDNEXT always advances even
when there are no messages to fetch.
2023-11-06 10:30:25 +00:00
link2xt
5549733a0b test: fix flaky test_forward_increation() test 2023-11-06 04:46:10 +00:00
link2xt
4e21917c0e feat: enable sync messages by default 2023-11-05 21:11:47 +00:00
bjoern
939b4b2aab feat: add 'group created instructions' as info message (#4916)
Before, it was shown by UI when the chat is empty, however, in case of
verified groups, this is never the case any longer as the 'e2ee now
guaranteed' is always added.
2023-11-05 19:24:34 +00:00
link2xt
fd0770859d chore(deltachat-jsonrpc): remove unused node-fetch dependency 2023-11-05 18:19:18 +00:00
link2xt
d5854fb3c9 chore(node): update @types/node 2023-11-05 18:16:37 +00:00
link2xt
3aa22a27cc chore(node): remove unused node-fetch dependency 2023-11-05 18:14:38 +00:00
link2xt
10b1a2f5f5 chore(node): update prettier dependency 2023-11-05 18:12:16 +00:00
link2xt
a28a34773c docs: remove documentation for non-existing dc_accounts_new os_name param 2023-11-05 17:54:00 +00:00
link2xt
7c744d14d7 docs: contact profile view should not use dc_contact_is_verified()
Green checkmark in the contact profile
should only be displayed in the title
if the same checkmark is displayed in the title of 1:1 chat.
If 1:1 chat does not exist,
the checkmark should not be displayed in the title
of the contact profile.

Also add docs to is_protected
property of FullChat and BasicChat JSON objects.
2023-11-05 17:21:23 +00:00
link2xt
6c68f2eb7e chore: update dependencies 2023-11-05 15:54:29 +00:00
link2xt
eb2d2b7313 refactor: accept &str instead of Option<String> in idle() 2023-11-05 15:32:37 +00:00
link2xt
2e50abedaa fix: check UIDNEXT with a STATUS command before going IDLE
This prevents accidentally going IDLE
when the last new message has arrived
while the folder was closed.
For example, this happened in some tests:
1. INBOX is selected to fetch, move and delete messages.
2. One of the messages is deleted.
3. INBOX is closed to expunge the message.
4. A new message arrives.
5. INBOX is selected with (CONDSTORE) to sync flags.
6. Delta Chat goes into IDLE without downloading the new message.

To determine that a new message has arrived
we need to notice that UIDNEXT has advanced when selecting the folder.
However, some servers such as Winmail Pro Mail Server 5.1.0616
do not return UIDNEXT in response to SELECT command.

To avoid interdependencies with the code
SELECTing the folder and having to implement
STATUS fallback after each SELECT even when we
may not want to go IDLE due to interrupt or unsolicited EXISTS,
we simply call STATUS unconditionally before IDLE.
2023-11-05 09:58:58 +01:00
link2xt
ee53136ed2 refactor: add hostname to "no DNS resolution results" error message 2023-11-05 09:58:33 +01:00
iequidoo
e923983dca fix: Synchronise self-chat
It just didn't work before, sync messages were not generated.
2023-11-04 19:16:35 -03:00
iequidoo
f4753862f1 feat: Sync chat state immediately (#4817)
Sync messages are only sent on explicit user actions and only one per action, so it's safe to send
them right away not worrying about the rate limit on the server.
2023-11-04 19:16:35 -03:00
link2xt
16b40f3a19 feat: hardcode mail.sangham.net into DNS cache 2023-11-04 17:48:57 +00:00
iequidoo
9cd3a7550b fix: Switch to EncryptionPreference::Mutual on a receipt of encrypted+signed message (#4707) 2023-11-03 23:32:02 -03:00
link2xt
d840a7e6b9 api!: remove deprecated get_verifier_addr 2023-11-03 23:17:09 +00:00
link2xt
d875691955 chore(cargo): update dependencies 2023-11-03 21:12:10 +00:00
bjoern
c600bfa8ca docs: refine Contact::get_verifier_id and Contact::is_verified documentation (#4922)
Co-authored-by: link2xt <link2xt@testrun.org>
2023-11-03 21:11:03 +00:00
link2xt
973ffa1a64 fix: allow to change verified key via "member added" message
"Member added" message likely happens because
the contact adding a new member has another
chat with the contact
2023-11-03 17:51:11 +00:00
link2xt
caffc3d93c fix(json-rpc): return verifier even if the contact is not verified
This may happen if autocrypt key is changed after verification.
UI should still display who introduced the contact,
especially if the contact is still a member of some verified group.
If the contact is at the same time not verified,
i.e. its autocrypt key does not match verified key,
UI may display a crossed out checkmark instead of green checkmark.
2023-11-03 17:51:11 +00:00
link2xt
a4dcf656f3 api: add JSON-RPC get_chat_id_by_contact_id API (#4918) 2023-11-03 13:55:07 +00:00
link2xt
7bb5d48966 refactor: improve error handling in securejoin code
Result::Err is reserved for local errors,
such as database failures.
Not found peerstate in the database is a protocol failure,
so just return Ok(false) in mark_peer_as_verified().

This allows to handle more errors with `?`.
2023-11-02 15:54:35 +00:00
holger krekel
71b7b0b393 fix doc strings for qr-code joinings 2023-11-02 13:31:35 +01:00
holger krekel
bd02eea66b refactor: remove unused or useless code paths in securejoin (#4897) 2023-11-02 12:29:48 +00:00
iequidoo
cdcb10fb58 refactor: Make SyncData::AlterChat an inline struct 2023-11-02 08:47:20 -03:00
iequidoo
6cd7296001 refactor: Replace Context::nosync flag with internal functions taking enum Sync (#4817) 2023-11-02 08:47:20 -03:00
iequidoo
168021523f feat: Sync Contact::blocked across devices (#4817) 2023-11-02 08:47:20 -03:00
iequidoo
03f2635296 feat: Sync chat mute_duration across devices (#4817) 2023-11-02 08:47:20 -03:00
iequidoo
e3b08fa92b feat: Sync chat visibility across devices (#4817) 2023-11-02 08:47:20 -03:00
iequidoo
79cebe66de feat: Sync chat Blocked state across devices (#4817) 2023-11-02 08:47:20 -03:00
link2xt
0619e2a129 chore(release): prepare for 1.128.0 2023-11-02 01:53:42 +00:00
Simon Laux
64a81e4f61 nodejs: update and fix typedoc 2023-11-02 01:27:08 +00:00
link2xt
0431ae53ca hack: decrease ratelimit for .testrun.org subdomains 2023-11-02 00:30:44 +00:00
Simon Laux
89c873acd0 changed!: upgrade nodejs version to 18 (#4903) 2023-11-02 01:23:48 +01:00
B. Petersen
2e70cf9388 remove comment pointing to nothing
documentation and reasoning is fully in `delete_chat()`,
the remove line does not add much to it, also, the hint to "above" is wrong.
2023-11-01 15:46:44 +01:00
link2xt
2efd0461d1 Revert "fix: add secondary verified key"
This reverts commit 5efb100f12.
2023-11-01 13:55:39 +00:00
holger krekel
196a34684d simplify "broken bobstate" as the state still passes 2023-11-01 00:58:54 +01:00
holger krekel
402fd6850c do the actual fix (thanks alex for some help) 2023-11-01 00:58:54 +01:00
holger krekel
72515f440d write a failing test 2023-11-01 00:58:54 +01:00
link2xt
045d919cdc refactor(deltachat-rpc-client): factor out resetup_account() 2023-10-31 23:08:57 +00:00
link2xt
9b9108320e refactor: avoid loading peerstate if there is no Autocrypt-Gossip 2023-10-31 23:08:57 +00:00
link2xt
5efb100f12 fix: add secondary verified key 2023-10-31 23:08:57 +00:00
link2xt
b747dd6ae8 refactor: remove unused argument from set_verified()
It is always PeerstateVerifiedStatus::BidirectVerified
and is always passed as a constant.
2023-10-31 23:08:57 +00:00
link2xt
ed2bc9e44d fix: remove previous attempt to recover from verified key change
This approach was introduced in the C core before Rust conversion:
<ced88321eb>
It does not have tests and does not practically help,
so we remove it in favor of alternative discussed in
<https://github.com/deltachat/deltachat-core-rust/issues/4541>
2023-10-31 23:08:57 +00:00
link2xt
9e1a2149fa test: test recovery of verified group via gossip 2023-10-31 23:08:57 +00:00
link2xt
22b6d8c17b feat(deltachat-rpc-client): add Account.wait_for_incoming_msg_event() 2023-10-31 23:08:57 +00:00
link2xt
3876846410 refactor: sort member vector before deduplicating
Otherwise SELF contact in the beginning of the vector
and in to_ids may be repeated twice and not deduplicated.
dedup() only deduplicates consecutive elements.
2023-10-31 23:08:57 +00:00
link2xt
a93c79e001 fix: allow other verified group recipients to be unverified
We may not have a verified key for other members
because we lost a gossip message.
Still, if the message is signed with a verified key
of the sender, there is no reason to replace it with an error.
2023-10-31 23:08:57 +00:00
link2xt
6aae0276da test: use instant accounts instead of mailadm 2023-10-30 00:15:22 +00:00
link2xt
1d80659bc3 chore: update portable-atomic dependency
Version 1.5.0 is yanked.
2023-10-29 23:36:26 +00:00
link2xt
94d5e86d4f refactor: rename repl_msg_by_error into replace_msg_by_error
This function has been named like this since it was a C function.
`repl` is unclear because it may stand for `reply`
as well as `replace`.
2023-10-29 17:09:59 +00:00
link2xt
aecf7729d8 chore(release): prepare for 1.127.2 2023-10-29 16:29:04 +00:00
Simon Laux
f130d537b7 api(jsonrpc): add get_message_info_object 2023-10-29 16:26:01 +00:00
Ajay Gonepuri
f30f862e7e docs: fix typos 2023-10-29 13:13:44 +00:00
link2xt
81e1164358 test: compile deltachat-rpc-server in debug mode for tests
This reduces compilation times.
2023-10-29 01:09:35 +00:00
Simon Laux
542bd4cbb8 api!: jsonrpc misc_set_draft now requires setting the viewtype 2023-10-28 08:42:14 +00:00
link2xt
771b57778e test: increase pytest timeout to 10 minutes
deltachat-rpc-client tests often timeouts on CI,
this hopefully fixes the problem unless the tests actually deadlock.
2023-10-28 00:54:36 +00:00
link2xt
9be56a5e56 test(deltachat-rpc-client): test securejoin 2023-10-27 20:07:32 +00:00
link2xt
da744958c2 chore: move pytest option from pyproject.toml to tox.ini and set log level
The option from pyproject.toml was not picked up
because tox.ini has higher precedence.
2023-10-27 20:00:20 +00:00
link2xt
f6bda1e480 docs: add missing 1.127.1 link to changelog 2023-10-27 19:34:49 +00:00
link2xt
d2e24534c7 chore(release): prepare for 1.127.1 2023-10-27 19:27:40 +00:00
link2xt
df6f974eca Add scripts for running deltachat-rpc-client tests 2023-10-27 17:24:39 +00:00
link2xt
2f5c6b5e16 test(jsonrpc): test get_provider_info 2023-10-27 03:07:47 +00:00
link2xt
97176b13f1 api(jsonrpc): add id to ProviderInfo 2023-10-27 03:07:18 +00:00
link2xt
18bb7e58be refactor: move api/mod.rs to api.rs 2023-10-27 02:33:17 +00:00
Simon Laux
c2bab44bdd api: jsonrpc add .is_protection_broken to FullChat and BasicChat 2023-10-27 00:03:12 +00:00
link2xt
53bb8a9831 chore: update to async-channel 2 2023-10-26 23:41:34 +00:00
link2xt
1b66120e7d chore(release): prepare for 1.127.0 2023-10-26 15:54:48 +00:00
link2xt
1478f321ae fix: restore try_many_times workaround
Even though r2d2 connection pool is removed,
deleting accounts still fails in Windows CI.

This reverts commit e88f21c010.
`try_many_times` documentation is modified to explain
why the workaround is still needed.
2023-10-26 15:15:44 +00:00
link2xt
5fb92c78ad ci: test deltachat-rpc-client on Windows 2023-10-26 15:15:44 +00:00
link2xt
a0a792b821 chore: update sct, serde and serde_derive 2023-10-26 14:06:44 +00:00
link2xt
3feb0e648d build: switch to iroh 0.4.x fork with updated dependencies 2023-10-26 14:04:32 +00:00
link2xt
fa5358a5bf chore: update tracing 2023-10-26 13:17:54 +00:00
Sebastian Klähn
7399a398a7 api: add mailto parse api (#4829)
close #4620 

This PR introduces a new core API to parse mailto links into a uniform
data format. This could be used to unify the different implementations
on the current platforms.
To complete this PR we have to decide for which APIs we want to expose
this (now) internal API (c, python, json-rpc, etc.), and if we want such
an API at all as it doesn't have a corresponding UI-PR and is not
_really_ needed.
2023-10-26 11:46:51 +02:00
link2xt
25a78aceb9 ci: increase MSRV to 1.70.0
This is required by `anstyle v1.0.4` dependency.
2023-10-26 02:16:10 +00:00
link2xt
66708454dd chore: update dependencies 2023-10-26 02:13:15 +00:00
link2xt
bb5e3d11d8 chore: update futures-lite dependency 2023-10-26 01:11:11 +00:00
link2xt
ff54db2e5f test: adapt the test for updated chrono 2023-10-26 00:47:32 +00:00
link2xt
434d8fc35f chore: update quick-xml 2023-10-25 22:42:14 +00:00
link2xt
12eb813bc3 ci(concourse): replace master branch with main 2023-10-25 22:02:35 +00:00
link2xt
88d5576150 ci(github): replace references to master branch with main 2023-10-25 22:02:32 +00:00
link2xt
af35e4adeb chore: update dependencies 2023-10-25 21:58:13 +00:00
link2xt
eaeacb8848 ci: run only on main branch pushes 2023-10-25 21:46:09 +00:00
link2xt
f00e68e142 chore: update some dependencies 2023-10-25 21:45:22 +00:00
link2xt
113356a24e docs: fix CI badge URL in the readme 2023-10-25 19:31:22 +00:00
link2xt
b89c134e7f Merge branch 'master' into stable 2023-10-25 16:50:18 +00:00
link2xt
3748794048 fix(sql): order migrations the same as on stable branch 2023-10-25 16:37:39 +00:00
iequidoo
ccca12176e feat: Replace Config::SendSyncMsgs with SyncMsgs (#4817)
And execute sync messages only if `Config::SyncMsgs` is enabled. Earlier executing was always
enabled, the messages are force-encrypted anyway. But for users it's probably more clear whether a
device is synchronised or not.
2023-10-25 04:47:37 -03:00
dependabot[bot]
c89dd331f7 chore(cargo): bump libc from 0.2.147 to 0.2.149
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.147 to 0.2.149.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.147...0.2.149)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-25 03:10:25 +00:00
link2xt
fa81ed5f39 ci: rename async tests into JSON-RPC tests 2023-10-25 01:33:56 +00:00
link2xt
6c34f6b8d9 ci: remove misplaced comment 2023-10-25 01:33:56 +00:00
dependabot[bot]
4f21a5691d chore(cargo): bump tokio from 1.29.1 to 1.33.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.29.1 to 1.33.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.29.1...tokio-1.33.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-25 00:56:33 +00:00
dependabot[bot]
b2a839971b chore(cargo): bump strum_macros from 0.25.1 to 0.25.3
Bumps [strum_macros](https://github.com/Peternator7/strum) from 0.25.1 to 0.25.3.
- [Changelog](https://github.com/Peternator7/strum/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Peternator7/strum/commits)

---
updated-dependencies:
- dependency-name: strum_macros
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-24 23:01:25 +00:00
link2xt
8ad99be322 ci: increase MSRV to 1.67.0 2023-10-24 21:18:15 +00:00
link2xt
4e771e8727 Merge branch 'stable' 2023-10-24 17:49:23 +00:00
Sebastian Klähn
e725bdfb2b feat: add bot field to contact (#4821)
closes #4647
2023-10-24 17:42:29 +00:00
link2xt
ac557f73b3 chore: remove unneeded idna rule for cargo-deny 2023-10-24 17:02:16 +00:00
link2xt
0ba3501a46 chore: update trust-dns-resolver to hickory-resolver 2023-10-24 17:00:14 +00:00
B. Petersen
b1fe12881e document configured_addr
in fact, it was already used like that,
eg. to detect an AEAP change on android.
but it was never documented officially.
2023-10-24 17:59:19 +02:00
link2xt
c1eb33c0da Merge tag 'v1.126.1'
Release 1.126.1
2023-10-24 14:50:49 +00:00
link2xt
03bb92c942 chore(release): prepare for 1.126.1 2023-10-24 14:30:02 +00:00
link2xt
b0da5a54cc chore(cargo): update ahash to make cargo-deny happy 2023-10-23 21:56:14 +00:00
link2xt
44e056e210 ci: build Windows wheels for deltachat-rpc-server 2023-10-23 20:38:58 +00:00
link2xt
48a8680ba4 build: set 755 permission on binaries inside deltachat-rpc-server .whl 2023-10-23 20:20:28 +00:00
link2xt
b73bcc2c22 ci: build macOS wheels for deltachat-rpc-server 2023-10-23 20:20:14 +00:00
link2xt
cff42936aa ci: add missing .exe suffix to windows deltachat-rpc-server paths 2023-10-23 20:19:35 +00:00
link2xt
d3b04004b4 feat(imap): buffer STARTTLS command
Using BufWriter ensures that `STARTTLS` command is sent
as a single packet.

Also refactor the code to ensure we only convert to
Box<dyn SessionStream> in the end.
2023-10-23 16:26:29 +00:00
link2xt
5cd92f10ef ci: build deltachat-rpc-server binaries for aarch64 macOS 2023-10-23 16:02:36 +00:00
link2xt
22a3ab983b refactor: download messages without jobs 2023-10-23 11:52:47 +00:00
link2xt
83d2e6b8b4 fix: do not interrupt IMAP loop from get_connectivity_html()
Android calls get_connectivity_html()
every time connectivity changes, which in turn interrupts
IMAP loop and triggers change from "not connected" to "connecting"
state.

To avoid such infinite loop of IMAP interrupts when
there is not connectivity, update quota only when IMAP
loop is interrupted otherwise. This anyway happens
when a message is received or maybe_network is called.

Also remove outdated comments about `Action::UpdateRecentQuota` job
which does not exist anymore.
2023-10-22 18:48:14 +00:00
link2xt
4e979c5880 build: make source package for deltachat-rpc-server install fixed version 2023-10-22 17:49:03 +00:00
link2xt
71e1089139 fix: do not hardcode version in deltachat-rpc-server source package 2023-10-22 16:46:26 +00:00
link2xt
349c154a99 ci: attempt to fix artifacts download for deltachat-rpc-server
Had to do this step manually for 1.126.0,
hopefully the step will work automatically for 1.127.0.
2023-10-22 15:24:02 +00:00
link2xt
54410dbe49 Merge tag 'v1.126.0' 2023-10-22 15:16:11 +00:00
link2xt
4e08bb7b05 chore(release): prepare for 1.126.0 2023-10-22 14:01:07 +00:00
Asiel Díaz Benítez
934ca6a7d7 api: add send_draft() to JSON-RPC API (#4839) 2023-10-22 13:14:08 +00:00
link2xt
e878caebe3 ci: build Python wheels for deltachat-rpc-server 2023-10-22 13:13:04 +00:00
link2xt
088eda2983 build(scripts/zig-rpc-server.sh): move built binaries to dist/ 2023-10-22 13:13:04 +00:00
link2xt
418cd24979 build: strip release binaries
This significantly reduces binary size for deltachat-rpc-server,
from 42 MiB to 15 MiB in case of aarch64.
2023-10-22 13:13:04 +00:00
link2xt
b4fe9e3eec build: use Zig via ziglang PyPI package
This avoids cluttering workdir with unpacked tarball
and will work automatically once PEP-723 is implemented.
2023-10-22 13:13:04 +00:00
link2xt
c13bbd05cd chore: add dist/ to .gitignore 2023-10-22 13:13:04 +00:00
link2xt
58330fe8b2 ci: remove musl check
It requires installing Zig and slows down CI.
This was not broken for a while and we can do
more frequent core releases to catch problems.
2023-10-22 13:13:04 +00:00
link2xt
680d024b05 docs: document scripts/codespell.sh 2023-10-22 06:53:44 +00:00
link2xt
defcd5764b chore: spellcheck 2023-10-22 06:53:26 +00:00
link2xt
e87f785a0a test: adjust expected info message in test_verified_group_vs_delete_server_after
Test was written for stable branch
and has to be adjusted for verified 1:1 chats branch
2023-10-21 04:18:39 +00:00
link2xt
0227bbc305 fix(imap): fallback to STATUS if SELECT did not return UIDNEXT
Winmail Pro Mail Server 5.1.0616 does not return UIDNEXT
in response to SELECT, but returns it when explicitly requested
via STATUS command:

    ? SELECT INBOX
    * FLAGS (\Draft \Answered \Flagged \Deleted \Seen \Recent)
    * OK [PERMANENTFLAGS (\Draft \Answered \Flagged \Deleted \Seen)] Limited
    * 2 EXISTS
    * 0 RECENT
    * OK [UIDVALIDITY 1697802109] Ok
    ? OK [READ-WRITE] Ok SELECT completed
    ? STATUS INBOX (UIDNEXT)
    * STATUS "INBOX" (UIDNEXT 4)
    ? OK STATUS completed

Previously used FETCH method is reported to fail for some users,
the FETCH command sometimes returns no results.
Besides, there is no guarantee that the message with
the highest sequence number has the highest UID.

In the worst case if STATUS does not return UIDNEXT
in response to explicit request, we fall back to setting
UIDNEXT to 1 instead of returning an error.
2023-10-20 22:29:44 +00:00
link2xt
d05afec289 chore(cargo): update async-imap to fix STATUS command 2023-10-20 22:29:44 +00:00
link2xt
64035d3ecb fix: set soft_heap_limit on SQLite database
This should prevent unlimited growth of memory usage
by SQLite for is page cache.
2023-10-20 05:18:21 +00:00
link2xt
21e0bb28ad build: create source distribution for deltachat-rpc-server 2023-10-19 14:38:03 +00:00
link2xt
c6358169ad fix: s/env/venv/ in scripts/make-python-testenv.sh 2023-10-18 20:10:51 +00:00
Asiel Díaz Benítez
955f4fbb19 add self-address to backup filename (#4820)
close #4816

---------

Co-authored-by: B. Petersen <r10s@b44t.com>
2023-10-18 12:31:32 -04:00
adbenitez
df7c44ae42 fix: wrong type hint 2023-10-17 17:18:25 +02:00
Hocuri
8573649bf7 feat: Make broadcast lists create their own chat (#4644)
feat: Make broadcast lists create their own chat - UIs need to ask for
the name when creating broadcast lists now (see
https://github.com/deltachat/deltachat-android/pull/2653)

That's quite a minimal approach: Add a List-ID header to outgoing
broadcast lists, so that the receiving Delta Chat shows them as a
separate chat, as talked about with @r10s and @hpk42.

Done:
- [x] Fix an existing bug that the chat name isn't updated when the
broadcast/mailing list name changes (I already started this locally)

To be done in other PRs:
- [ ] Right now the receiving side shows "Mailing list" in the subtitle
of such a chat, it would be nicer if it showed "Broadcast list" (or
alternatively, rename "Broadcast list" to "Mailing list", too)
- [ ] The UIs should probably ask for a name before creating the
broadcast list, since it will actually be sent over the wire. (Android
PR: https://github.com/deltachat/deltachat-android/pull/2653)

Fixes https://github.com/deltachat/deltachat-core-rust/issues/4597

BREAKING CHANGE: This means that UIs need to ask for the name when creating a broadcast list, similar to https://github.com/deltachat/deltachat-android/pull/2653.
2023-10-17 10:40:47 +02:00
link2xt
52c46c6dca build: add script to build deltachat-rpc-server wheels 2023-10-16 17:04:55 +00:00
link2xt
54ea3ec5d6 build: workaround OpenSSL crate expecting libatomic to be available 2023-10-15 22:57:46 +00:00
Sebastian Klähn
1632035784 feat: add bot field to contact (#4821)
closes #4647
2023-10-15 12:40:32 +02:00
Sebastian Klähn
b239535964 api: allow to filter by unread in chatlist:try_load (#4824)
close #4738
2023-10-14 11:12:53 +02:00
Sebastian Klähn
0751cc50b9 api(json-rpc): force stickers to be sent as stickers (#4819)
This approach uses a param field to enable forcing the sticker
`viewtype`. The first commit has the memory-only flag implemented, but
this flag is not persistent through the database conversion needed for
draft/undraft. That's why `param` has to be used.

follow up to #4814 
fixes #4739

---------

Co-authored-by: Septias <scoreplayer2000@gmail.comclear>
2023-10-14 08:34:46 +00:00
link2xt
da5d844ec4 chore: rustfmt 2023-10-14 04:25:13 +00:00
link2xt
2775fd1fcf Merge tag 'v1.125.0'
Release 1.125.0
2023-10-14 04:24:08 +00:00
link2xt
a87635dcf4 chore(release): prepare for 1.125.0 2023-10-14 04:21:48 +00:00
link2xt
e30517e62c refactor: log MDN sending errors 2023-10-14 03:29:20 +00:00
iequidoo
a54f3c4b31 fix: Don't try to send more MDNs if there's a tmp SMTP error (#4534)
If there's a temporary SMTP error, pretend there are no more MDNs to send in send_mdn(). It's
unlikely that other MDNs could be sent successfully in case of connectivity problems. This approach
is simpler and perhaps even better than adding a progressive backoff between MDN sending retries --
MDNs just will be resent after a reconnection, which makes some sense.
2023-10-12 19:19:43 -03:00
iequidoo
bda6cea0ce feat: Make gossip period configurable (#4346)
This is needed to test periodic re-gossiping in existing chats.

Also add a test for verified groups on that even if "member added" message is missed by a device of
newly added member, after re-gossiping Autocrypt keys to the group it successfully learns these keys
and marks other members as verified.
2023-10-12 05:45:20 -03:00
iequidoo
6fece09ed7 test: test_qr_new_group_unblocked(): W/a message reordering on server
There was a recent failure of the test probably as a result of message reordering on the server:
https://github.com/deltachat/deltachat-core-rust/actions/runs/6464605602/job/17549624095?pr=4813.
2023-10-11 04:54:03 -03:00
link2xt
3917c6b2f0 test(deltachat-rpc-client): enable logs in pytest
This makes pytest setup a logger for `logging` module.
2023-10-10 19:20:42 +00:00
link2xt
96a89b5bdc fix: return verifier contacts regardless of their origin
Previously `Origin::AddressBook` was required,
resulting in a lot of
"Could not lookup contact with address ... which introduced ..."
warnings.
2023-10-10 19:20:22 +00:00
link2xt
b55027fe71 fix: set connectivity status to "connected" during fake idle
Set connectivity status to "connected" at the end of connect() call.
Otherwise for servers that do not support IMAP IDLE
connect() is called at the beginning of fake idle
and connectivity stays in "connecting" status most of the time.
2023-10-10 05:37:51 +00:00
link2xt
eacbb82399 feat: add developer option to disable IDLE 2023-10-10 00:52:18 +00:00
Sebastian Klähn
ee279f84ad fix: show all contacts in Contact::get_all for bots (#4811)
successor of #4810
2023-10-09 21:02:19 +02:00
link2xt
26959d5b75 test(python): fix flaky test_set_get_group_image
Wait for one "Member added" message to be delivered
before sending another text message.
Otherwise they may be reordered by the mail server.
2023-10-09 12:48:33 +00:00
link2xt
ff5005fa93 fix(python): fix scripts/make-python-testenv.sh
Without `-c python` tox does not find tox.ini and creates empty environment.

Renamed env/ into venv/ as it is more common.
2023-10-09 12:43:22 +00:00
iequidoo
8f316e12d5 fix: Assign encrypted partially downloaded group messages to 1:1 chat (#4757)
Before they were trashed. Note that for unencrypted ones DC works as expected creating the requested
group immediately because Chat-Group-Id is duplicated in the Message-Id header and Subject is
fetched.
2023-10-09 05:45:18 -03:00
iequidoo
5f00fc4e27 fix: Don't update timestamp, timestamp_rcvd, state when replacing partially downloaded message (#4700)
Also add a test on downloading a message later. Although it doesn't reproduce #4700 for some reason,
it fails w/o the fix because before a message state was changing to `InSeen` after a full download
which doesn't look correct. The result of a full message download should be such as if it was fully
downloaded initially.
2023-10-09 05:45:18 -03:00
link2xt
f279730b0f feat: validate boolean values passed to set_config
They may only be set to "0" and "1".
Validation prevents accidentally setting the value to "true", "True" etc.
2023-10-08 23:15:49 +00:00
missytake
5a5f8b03d1 fix(python): don't automatically set the displayname to 'bot' when setting log level 2023-10-08 17:38:57 +00:00
missytake
5e73e9cd72 chore: added more typical virtualenv paths to gitignore 2023-10-08 17:38:57 +00:00
link2xt
129de9182f chore(deltachat-rpc-client): remove AsyncIO classifier 2023-10-08 01:38:52 +00:00
link2xt
37383c10ac Merge 'stable' into 'master'
Resolved conflicts due to asyncio removal.
2023-10-08 01:30:46 +00:00
link2xt
09798df7a0 refactor(deltachat-rpc-client): remove print() calls 2023-10-07 23:50:38 +00:00
link2xt
b360225e08 refactor: fix Rust 1.73 clippy warnings 2023-10-06 21:21:16 +00:00
link2xt
09d5e44b13 ci: test with Rust 1.73 2023-10-06 21:21:16 +00:00
link2xt
8ba89c0fa1 ci: reduce required Python version for deltachat-rpc-client 2023-10-06 21:20:44 +00:00
link2xt
f984a27379 fix: use process_group Popen argument with Python 3.11 2023-10-06 19:40:26 +00:00
link2xt
425a2310fe refactor(deltachat-rpc-client): close stdin instead of sending SIGTERM 2023-10-06 18:44:19 +00:00
link2xt
95571be278 fix: run deltachat-rpc-server in its own process group
This ensures the server does not get SIGINT
when the bot is running in a terminal and user presses ^C
We want to send SIGTERM ourselves after clean shutdown,
e.g. stopping I/O for all accounts.
2023-10-06 18:30:59 +00:00
link2xt
7bf44a237e api(deltachat-rpc-client)!: replace asyncio with threads 2023-10-05 15:59:57 +00:00
link2xt
a119b24eeb Merge tag 'v1.124.1' 2023-10-05 05:02:18 +00:00
link2xt
47dbac9b50 chore(release): prepare for 1.124.1 2023-10-05 05:01:26 +00:00
link2xt
a49282727b ci: pin urllib3 version to <2
Otherwise it is impossible to build wheels.
2023-10-05 04:41:51 +00:00
iequidoo
0d22fc7ac1 fix: Remove footer from reactions on the receiver side (#4780)
Reactions do not have footer since 6d2ac30. However, mailing lists still add the footer to the
messages, and receiver interpreted words as a reaction.
2023-10-04 22:46:09 -03:00
link2xt
275791595c Merge tag 'v1.124.0' 2023-10-04 21:14:17 +00:00
link2xt
1040bc551f chore(release): prepare for 1.124.0 2023-10-04 21:12:38 +00:00
iequidoo
5aa0205c80 fix: Add protected-headers directive to Content-Type of encrypted/signed MIME (#2302)
Add protected-headers="v1" directive to Content-Type of an encrypted/signed MIME so that other MUAs
like Thunderbird display the true message Subject instead of "...".
2023-10-04 19:58:08 +00:00
link2xt
210a4ebcbe ci: test async python bindings with Python 3.11 2023-10-04 19:56:56 +00:00
link2xt
7fc2b06b3f ci(mypy): ignore distutils
Python 3.12 removed `distutils`.
`distutils` from `setuptools` work fine,
but have not typing stubs:
https://github.com/python/typeshed/issues/10255
2023-10-04 19:56:56 +00:00
link2xt
1177c19a43 bulid: build wheels for Python 3.12 and PyPy 3.10 2023-10-04 19:56:56 +00:00
link2xt
8a2417f32d ci: test with Python 3.12 and PyPy 3.10 2023-10-04 19:56:56 +00:00
link2xt
a154347834 fix(deltachat-rpc-client): increase stdio buffer to 64 MiB
Otherwise readline() gets stuck when JSON-RPC response
is longer that 64 KiB.
2023-10-04 16:08:15 +00:00
link2xt
d51adf2aa0 feat(deltachat-rpc-client): log exceptions when long-running tasks die
For example, reader_loop() may die
if readline() tries to read too large line
and thows an exception.
We want to at least log the exception in this case.
2023-10-04 08:22:50 +00:00
link2xt
a5f0c1613e fix: add Let's Encrypt root certificate to reqwest
This certificate does not exist on older Android phones.
It is already added manually for IMAP and SMTP,
this commit adds the same certificate for HTTP requests.
2023-10-03 19:35:39 +00:00
link2xt
7c4bcf9004 api!: deprecate get_next_media() 2023-10-03 16:08:25 +00:00
dependabot[bot]
f3fb0dc5fe chore(cargo): bump proptest from 1.2.0 to 1.3.1
Bumps [proptest](https://github.com/proptest-rs/proptest) from 1.2.0 to 1.3.1.
- [Release notes](https://github.com/proptest-rs/proptest/releases)
- [Changelog](https://github.com/proptest-rs/proptest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/proptest-rs/proptest/compare/v1.2.0...v1.3.1)

---
updated-dependencies:
- dependency-name: proptest
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-03 01:34:58 -03:00
dependabot[bot]
24ea90bd68 Merge pull request #4770 from deltachat/dependabot/cargo/thiserror-1.0.49 2023-10-03 04:30:28 +00:00
dependabot[bot]
ef3e94c7e1 Merge pull request #4777 from deltachat/dependabot/cargo/fuzz/webpki-0.22.2 2023-10-03 04:14:01 +00:00
dependabot[bot]
883832f78d Merge pull request #4768 from deltachat/dependabot/cargo/brotli-3.4.0 2023-10-03 01:21:32 +00:00
dependabot[bot]
1f03267273 Merge pull request #4773 from deltachat/dependabot/cargo/sha2-0.10.8 2023-10-03 01:21:20 +00:00
dependabot[bot]
8bc2ce1c30 chore(deps): bump webpki from 0.22.0 to 0.22.2 in /fuzz
Bumps [webpki](https://github.com/briansmith/webpki) from 0.22.0 to 0.22.2.
- [Commits](https://github.com/briansmith/webpki/commits)

---
updated-dependencies:
- dependency-name: webpki
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-02 21:39:40 +00:00
dependabot[bot]
2ae92c06e3 Merge pull request #4771 from deltachat/dependabot/cargo/regex-1.9.6 2023-10-02 17:46:17 +00:00
dependabot[bot]
4a6a214f3c Merge pull request #4769 from deltachat/dependabot/cargo/tokio-util-0.7.9 2023-10-02 16:38:54 +00:00
dependabot[bot]
c2d7011aa7 Merge pull request #4772 from deltachat/dependabot/cargo/smallvec-1.11.1 2023-10-02 16:38:16 +00:00
dependabot[bot]
c0195ab23f chore(cargo): bump sha2 from 0.10.7 to 0.10.8
Bumps [sha2](https://github.com/RustCrypto/hashes) from 0.10.7 to 0.10.8.
- [Commits](https://github.com/RustCrypto/hashes/compare/sha2-v0.10.7...sha2-v0.10.8)

---
updated-dependencies:
- dependency-name: sha2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:44:09 +00:00
dependabot[bot]
e4e50d0e81 chore(cargo): bump smallvec from 1.11.0 to 1.11.1
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.11.0 to 1.11.1.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.11.0...v1.11.1)

---
updated-dependencies:
- dependency-name: smallvec
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:43:50 +00:00
dependabot[bot]
573746ce54 chore(cargo): bump regex from 1.9.5 to 1.9.6
Bumps [regex](https://github.com/rust-lang/regex) from 1.9.5 to 1.9.6.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.9.5...1.9.6)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:43:32 +00:00
dependabot[bot]
6b2df13cdb chore(cargo): bump thiserror from 1.0.47 to 1.0.49
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.47 to 1.0.49.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.47...1.0.49)

---
updated-dependencies:
- dependency-name: thiserror
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:43:13 +00:00
dependabot[bot]
3166b44580 chore(cargo): bump tokio-util from 0.7.8 to 0.7.9
Bumps [tokio-util](https://github.com/tokio-rs/tokio) from 0.7.8 to 0.7.9.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-util-0.7.8...tokio-util-0.7.9)

---
updated-dependencies:
- dependency-name: tokio-util
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:42:54 +00:00
dependabot[bot]
e500485c21 chore(cargo): bump brotli from 3.3.4 to 3.4.0
Bumps [brotli](https://github.com/dropbox/rust-brotli) from 3.3.4 to 3.4.0.
- [Release notes](https://github.com/dropbox/rust-brotli/releases)
- [Commits](https://github.com/dropbox/rust-brotli/commits)

---
updated-dependencies:
- dependency-name: brotli
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-01 21:42:27 +00:00
B. Petersen
2dd44d5f89 fix: cap percentage in connectivity layout to 100%
it may happen that percentages larger than 100% are reported by the provider,
eg. for some time a storage usage of 120% may be accepted.

while we should report the values "as is" to the user,
for the bar, percentages larger 100% will destroy the layout.
2023-10-01 14:54:37 +00:00
link2xt
f656cb29be fix: ignore special chats in get_similar_chat_ids()
For unknown reason trash chat contains members in some existing databases.
Workaround this by ignoring chats_contacts entries with special chat_id.
2023-10-01 07:38:13 +00:00
link2xt
59e5a63d5f Merge branch 'stable', resolving conflicts 2023-10-01 02:46:02 +00:00
link2xt
53230b6eb0 chore(cargo): update webpki to fix RUSTSEC-2023-0052 2023-10-01 00:04:45 +00:00
iequidoo
80ca59f152 feat: Remove extra members from the local list in sake of group membership consistency (#3782)
9bd7ab72 brings a possibility of group membership inconsistency to the original Hocuri's algo
described and implemented in e12e026b in sake of security so that nobody can add themselves to a
group by forging "InReplyTo" and other headers. This commit fixes the problem by removing group
members locally if we see a discrepancy with the "To" list in the received message as it is better
for privacy than adding absent members locally. But it shouldn't be a big problem if somebody missed
a member addition, because they will likely recreate the member list from the next received
message. The problem occurs only if that "somebody" managed to reply earlier. Really, it's a problem
for big groups with high message rate, but let it be for now.

Also:
- Query chat contacts from the db only once.
- Update chat contacts in the only transaction, otherwise we can just break the chat contact list
  halfway.
- Allow classic MUA messages to remove group members if a parent message is missing. Currently it
  doesn't matter because unrelated messages go to new ad-hoc groups, but let this logic be outside
  of apply_group_changes(). Just in case if there will be a MUA preserving "Chat-Group-ID" header
  f.e.
2023-09-30 19:14:22 -03:00
link2xt
eb624e43c0 refactor: remove incomplete protected header code skipping Legacy Display Part
The code removed is an incomplete implementation of skipping
the Legacy Display Part specified in
https://www.ietf.org/archive/id/draft-autocrypt-lamps-protected-headers-02.html#section-5.2

The code does not fully implement the specification, e.g.
it does not check that there are exactly two parts.

Delta Chat and Thunderbird are not adding this part anyway,
and it is defined as "transitional" in the draft.

This also removes misplaced warning "Ignoring nested protected headers"
that is printed for every incoming Delta Chat message
since commit 5690c48863
which is part of the PR <https://github.com/deltachat/deltachat-core-rust/pull/982>.
2023-09-30 21:54:08 +00:00
link2xt
532e9cb09a refactor: ignore public key argument in dc_preconfigure_keypair()
Public key can be extracted from the secret key file.
2023-09-30 19:16:23 +00:00
link2xt
ef4d2a7ed0 api!(python): use dc_contact_get_verifier_id()
get_verifier() returns a Contact rather than an address now

dc_contact_get_verifier_addr() is unused.
2023-09-30 15:49:22 +00:00
link2xt
5daa6274e8 Merge stable into master 2023-09-30 12:16:51 +00:00
link2xt
6d2ac30461 fix: do not put the status footer into reaction MIME parts 2023-09-29 16:38:55 +00:00
Hocuri
d109a1b27f Fix link to the template documentation of git-cliff
The old link gives me 404
2023-09-29 15:20:22 +00:00
link2xt
33a203d56e fix: initialise last_msg_id to the highest known row id
Otherwise existing bots migrating to get_next_msgs()
are trying to process all the messages they have in the database.
2023-09-29 13:28:58 +00:00
link2xt
a19811f379 chore(cargo): update tungstenite to fix RUSTSEC-2023-0065
Used `cargo update -p axum`.
2023-09-29 13:08:04 +00:00
link2xt
f23023961e api!: return DC_CONTACT_ID_SELF from dc_contact_get_verifier_id() for directly verified contacts 2023-09-28 19:10:15 +00:00
link2xt
b463a0566e refactor: flatten create_or_lookup_mailinglist() 2023-09-28 15:20:51 +00:00
link2xt
38d5743c06 refactor: do not ignore errors in get_kml()
This removes unnecessary warning
"mimefactory: could not send location: No locations processed"
when there are no locations to send.
2023-09-28 15:19:33 +00:00
link2xt
6990312051 fix: trash only empty *text* parts when location.kml is attached
If the message contains other attachment parts
such as images, they should not go into trash.
2023-09-27 18:51:40 +00:00
link2xt
a7cf51868b test: test send_location 2023-09-27 18:51:40 +00:00
link2xt
815c1b9c49 refactor: resultify location::set() 2023-09-27 18:51:40 +00:00
link2xt
88bba83383 refactor: flatten process_report() 2023-09-26 16:02:14 +00:00
WofWca
b1d517398d refactor: improve comment about Ratelimit
A few people got the impression that if you send 6 messages
in a burst you'll only be able to send the next one in 60 seconds.
Hopefully this can resolve it.
2023-09-26 15:58:24 +00:00
link2xt
4e5b41f150 fix: require valid email addresses in dc_provider_new_from_email[_with_dns]() 2023-09-25 15:51:10 +00:00
B. Petersen
56b2361f01 reset document.update on forwarding
this fixes the test test_forward_webxdc_instance()
2023-09-25 15:20:57 +00:00
B. Petersen
968cc65323 test that update.document is not forwarded
the test is failing currently
2023-09-25 15:20:57 +00:00
link2xt
d0ee21e6dc refactor: flatten GENERATED_PREFIX check in receive_imf_inner 2023-09-25 10:35:07 +00:00
link2xt
a1345f2542 refactor: flatten lookup_chat_by_reply 2023-09-25 10:34:20 +00:00
link2xt
f290fe0871 fix: wrap base64-encoded parts to 76 characters
This is an RFC 2045 requirement for base64-encoded MIME parts.
Previously referenced RFC 5322 requirement
is a general Internet Message Format requirement
and is more generous.
2023-09-25 10:33:46 +00:00
dependabot[bot]
c41687586c Merge pull request #4742 from deltachat/dependabot/cargo/fuzz/quinn-proto-0.9.5 2023-09-22 22:43:28 +00:00
link2xt
59a3bc0ff4 Merge tag 'v1.123.0' 2023-09-22 22:41:08 +00:00
link2xt
aa78e82fed chore(release): prepare for 1.123.0 2023-09-22 22:13:47 +00:00
link2xt
d4e670d5e9 chore(deps): update OpenSSL from 3.1.2 to 3.1.3 2023-09-22 21:57:36 +00:00
link2xt
4553c6521f api!: make dc_jsonrpc_blocking_call accept JSON-RPC request 2023-09-22 21:33:52 +00:00
dependabot[bot]
a42a6ca18c chore(deps): bump quinn-proto from 0.9.2 to 0.9.5 in /fuzz
Bumps [quinn-proto](https://github.com/quinn-rs/quinn) from 0.9.2 to 0.9.5.
- [Release notes](https://github.com/quinn-rs/quinn/releases)
- [Commits](https://github.com/quinn-rs/quinn/commits)

---
updated-dependencies:
- dependency-name: quinn-proto
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-21 17:26:12 +00:00
link2xt
e72d527d88 api: make it possible to import secret key from a file
Previously it was required that a directory path is provided to the import API.
Now it is possible to point directly to the .asc file containing a secret key.

This allows UI to present a file selection dialog to the user
and let select the file directly.

Selecting a directory is still supported for backwards compatibility.
2023-09-20 16:18:45 +00:00
link2xt
f5c36043f6 fix(imex): use "default" in the filename of the default key
Previously the logic was inverted, default key was exported with a number
and all other keys were exported into "default".
2023-09-20 16:18:45 +00:00
iequidoo
b227ff87dc fix: lookup_chat_by_reply(): Skip undecipherable parent messages created by older versions (#4676)
It's just a dirty hack checking the error prefix, but as undecipherable messages are remembered in
the db now, the hack may be removed soon.
2023-09-18 14:55:56 +00:00
iequidoo
676f311f97 fix: lookup_chat_by_reply(): Skip not fully downloaded and undecipherable messages (#4676)
Such a message may be assigned to a wrong chat (e.g. undecipherable group msgs often get assigned to
the 1:1 chat with the sender). Add `DownloadState::Undecipherable` so that messages referencing
undecipherable ones don't go to that wrong chat too. Also do not reply to not fully downloaded
messages. Before `Message.error` was checked for that purpose, but a message can be error for many
reasons.
2023-09-18 14:55:56 +00:00
link2xt
061d091c97 build(coredeps): only run yum if it is available
musllinux is based on Alpine and has no yum
2023-09-12 19:59:15 +00:00
link2xt
e7617f0abd build(coredeps): install perl-IPC-Cmd
It is required to configure OpenSSL 3.0.
2023-09-12 19:02:20 +00:00
link2xt
790e867af0 Merge tag 'v1.122.0' 2023-09-12 18:04:05 +00:00
link2xt
f02299c06c chore(release): prepare for 1.122.0 2023-09-12 17:33:22 +00:00
link2xt
ed781af52c chore(cargo): update to OpenSSL 3.0
OpenSSL 1.1.1 has reached End of Life:
https://www.openssl.org/blog/blog/2023/09/11/eol-111/
2023-09-12 17:11:58 +00:00
link2xt
67043177a9 fix: reopen all connections on database passpharse change
Previously only one connection, the one used to change the key,
was working after passphrase change.

With this fix the whole pool of connections
is recreated on passphrase change, so there is no need
to reopen the database manually.
2023-09-12 16:34:26 +00:00
link2xt
49cc5fb673 feat: add RSA-4096 key generation support 2023-09-12 12:33:34 +00:00
link2xt
68c95dee17 refactor(pgp): add constants for encryption algorithm and hash
These constants are current defaults in `pgp` crate,
this change would prevent accidental change due to rPGP upgrade
and make it easier to change in a single place.
2023-09-12 11:12:59 +02:00
iequidoo
9bd7ab7280 fix: apply_group_changes(): Forbid membership changes from possible non-members (#3782)
It can be not good for membership consistency if we missed a message adding a member, but improves
security because nobody can add themselves to a group from now on.
2023-09-12 00:30:02 -03:00
link2xt
7a359f6318 build(python): add link to mastodon into projects.urls
Such links are displayed on PyPI with mastodon icon.
2023-09-11 04:47:55 +00:00
link2xt
38b31aa88d fix: do not block new group chats if 1:1 chat is blocked
1:1 chat may be blocked while the contact is not
if 1:1 chat was created as a result of scanning
a verified group join QR code with the contact
as the inviter. In this case 1:1 chat is blocked to hide it
while the contact is unblocked.
2023-09-10 21:44:56 +00:00
iequidoo
e12e026bd8 fix: Switch to original Hocuri's group membership consistency algo (#3782)(#4624)
- If we don't know the parent (=In-Reply-To) message, then completely recreate the group member list
  (i.e. use the member list of the incoming message) (because we assume that we missed some messages
  & have a wrong group state).
- If the message has a "Chat-Group-Member-Removed: member@example.com" header, then remove this
  member.
- If the message has a "Chat-Group-Member-Added: member@example.com" header, then add this member.

That means:
- Remove checks for the presense of `ContactId::SELF` in the group. Thus all recipients of a message
  take the same decision about group membership changes, no matter if they are in the group
  currently. This fixes a situation when a recipient thinks it's not a member because it missed a
  message about its addition before.
  NOTE: But always recreate membership list if SELF has been added. The older versions of DC don't
  always set "In-Reply-To" to the latest message they sent, but to the latest delivered message (so
  it's a race), so we need this heuristic currently.
- Recreate the group member list if we don't know the parent (=In-Reply-To) message, even if the
  sender isn't in the group as per our view, because we missed some messages and our view may be
  stale.
2023-09-09 16:22:13 -03:00
iequidoo
212fbc125c fix: ChatId::parent_query(): Don't filter out OutPending and OutFailed messages
The new message for which `parent_query()` is done may assume that it will be received in a context
affected by those messages, e.g. they could add new members to a group and the new message will
contain them in "To:". Anyway recipients must be prepared to orphaned references.
2023-09-09 16:22:13 -03:00
link2xt
2939de013b api(jsonrpc): return only chat IDs for similar chats
This is already the way `get_chatlist_entries` works.

`get_similar_chatlist_entries` is renamed into
`get_similar_chat_ids` because return values are not entries anymore.
2023-09-08 18:47:31 +00:00
link2xt
4a0585404a chore(cargo): bump webpki from 0.22.0 to 0.22.1 2023-09-08 07:00:55 +00:00
link2xt
0562e23ee0 chore(cargo): bump webpki from 0.22.0 to 0.22.1 2023-09-08 07:00:18 +00:00
link2xt
dcbf5996c2 Merge tag 'v1.121.0' 2023-09-06 21:46:07 +00:00
link2xt
a8551510cd chore(release): prepare for 1.121.0 2023-09-06 20:53:00 +00:00
link2xt
087f6edd0c refactor: make set_msg_failed accept &mut Message instead of MsgId 2023-09-06 20:33:37 +00:00
link2xt
d6b7ee04a0 docs: document range argument of render_webxdc_status_update_object() 2023-09-06 20:33:37 +00:00
link2xt
d5c5ff8b3f refactor: accept &mut Message in create_send_msg_job() 2023-09-06 20:33:37 +00:00
link2xt
dc4396a699 fix: update passed by reference Message in prepare_msg_raw() 2023-09-06 20:33:37 +00:00
link2xt
a74b00c3f9 refactor: move try_calc_and_set_dimensions() call to prepare_msg_blob() 2023-09-06 20:33:37 +00:00
link2xt
2fdb9f8b7e fix: do not ignore errors in try_calc_and_set_dimensions 2023-09-06 20:33:37 +00:00
link2xt
80fac3f1b8 refactor: use let-else in resend_msgs() 2023-09-06 20:33:37 +00:00
link2xt
17a6c88cc7 api: add Message.set_file_from_bytes() API 2023-09-06 20:33:37 +00:00
link2xt
1ba69dbb9b fix: reset MIME type if passed to set_file value is None 2023-09-06 20:33:37 +00:00
link2xt
ab1c7ebbe2 refactor: remove unnecessary local variable save_param 2023-09-06 20:33:37 +00:00
link2xt
ee715da078 fix: do not ignore chat loading errors in forward_msgs() 2023-09-06 20:33:37 +00:00
link2xt
27e177dc05 refactor: resultify set_msg_failed() 2023-09-06 20:33:37 +00:00
link2xt
7aac4bfc83 docs: document WebXDC-related SQL tables 2023-09-06 20:33:37 +00:00
link2xt
7b24f9b7a4 docs: comment that msgs_status_updates.update_item_read column is unused 2023-09-06 20:33:37 +00:00
link2xt
b36b902eeb build: build node packages on Ubuntu 18.04
Debian 10 has glibc 2.28, so packages built with it
do not work on Ubuntu 18.04.
2023-09-06 17:23:04 +00:00
dependabot[bot]
f7a47e60cd Merge pull request #4664 from deltachat/dependabot/cargo/strum_macros-0.25.2 2023-09-05 19:08:04 +00:00
link2xt
30024abb6c feat: add API to get similar chats 2023-09-05 16:47:19 +00:00
link2xt
1d9702e9e7 refactor: add ChatId::get_timestamp() 2023-09-05 16:47:19 +00:00
link2xt
ee2eae63d6 fix: do not allow dots at the end of email addresses 2023-09-05 13:14:37 +00:00
link2xt
cd477936b5 api: add dc_context_change_passphrase() 2023-09-05 12:41:31 +00:00
Hocuri
2587ebbacd fix: Clear VerifiedOneOnOneChats config on backup (#4681)
If the user makes a backup from a UI that supports the experimental verified 1:1 chats (e.g. nightly Android) and imports it into a UI that doesn't, then this config should be cleared.

We already talked about this a long time ago after @Simon-Laux noticed this problem, but I think we didn't actually solve it back then?

Best to review with whitespace changes disabled.
2023-09-05 09:15:15 +02:00
link2xt
dbe9d7e34e refactor(provider): create provider database entries at compile time
According to cargo-llvm-lines it reduces the number of lines
in the crate by 0.7%.
2023-09-05 00:03:34 +00:00
dependabot[bot]
4815e9b990 Merge pull request #4680 from deltachat/dependabot/cargo/regex-1.9.5 2023-09-05 00:03:09 +00:00
dependabot[bot]
f05b0ddf04 chore(cargo): bump regex from 1.9.1 to 1.9.5
Bumps [regex](https://github.com/rust-lang/regex) from 1.9.1 to 1.9.5.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.9.1...1.9.5)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-04 19:09:31 +00:00
link2xt
f94d34c94b chore: remove idna from deny.toml 2023-09-04 19:08:49 +00:00
link2xt
e9811fb6da AsyncResolver::tokio does not return a Result anymore 2023-09-04 19:08:49 +00:00
dependabot[bot]
178fc1736d chore(cargo): bump trust-dns-resolver from 0.22.0 to 0.23.0
Bumps [trust-dns-resolver](https://github.com/bluejekyll/trust-dns) from 0.22.0 to 0.23.0.
- [Release notes](https://github.com/bluejekyll/trust-dns/releases)
- [Changelog](https://github.com/bluejekyll/trust-dns/blob/main/CHANGELOG.md)
- [Commits](https://github.com/bluejekyll/trust-dns/compare/v0.22.0...v0.23.0)

---
updated-dependencies:
- dependency-name: trust-dns-resolver
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-04 19:08:49 +00:00
dependabot[bot]
54d632adaf chore(cargo): bump axum from 0.6.19 to 0.6.20
Bumps [axum](https://github.com/tokio-rs/axum) from 0.6.19 to 0.6.20.
- [Release notes](https://github.com/tokio-rs/axum/releases)
- [Changelog](https://github.com/tokio-rs/axum/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/axum/compare/axum-v0.6.19...axum-v0.6.20)

---
updated-dependencies:
- dependency-name: axum
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-04 19:08:34 +00:00
Hocuri
ae939e79da Merge remote-tracking branch 'origin/stable' 2023-09-04 19:19:50 +02:00
link2xt
49f143e0d5 refactor: make get_abs_path non-generic
Generic functions compile into multiple implementations,
increasing number of lines for LLVM to process,
code size and compilation times.
2023-09-04 00:43:24 +00:00
link2xt
9d7bdf369d refactor: use slices instead of vectors in provider database 2023-09-03 20:19:58 +00:00
dependabot[bot]
e12ef805a9 Merge pull request #4675 from deltachat/dependabot/cargo/backtrace-0.3.69 2023-09-03 19:50:35 +00:00
dependabot[bot]
b36acb2dc0 chore(cargo): bump log from 0.4.19 to 0.4.20
Bumps [log](https://github.com/rust-lang/log) from 0.4.19 to 0.4.20.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.19...0.4.20)

---
updated-dependencies:
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-03 02:25:33 +00:00
dependabot[bot]
1b883ae3fa chore(cargo): bump typescript-type-def from 0.5.7 to 0.5.8
Bumps [typescript-type-def](https://github.com/dbeckwith/rust-typescript-type-def) from 0.5.7 to 0.5.8.
- [Changelog](https://github.com/dbeckwith/rust-typescript-type-def/blob/master/CHANGELOG.md)
- [Commits](https://github.com/dbeckwith/rust-typescript-type-def/compare/v0.5.7...v0.5.8)

---
updated-dependencies:
- dependency-name: typescript-type-def
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-03 02:25:00 +00:00
dependabot[bot]
72c94e1037 chore(cargo): bump serde from 1.0.180 to 1.0.188
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.180 to 1.0.188.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.180...v1.0.188)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-03 02:24:33 +00:00
adbenitez
a270db1d87 remove aiodns optional dependency from required dependencies 2023-09-03 00:32:08 +00:00
dependabot[bot]
0a4c993bb8 chore(cargo): bump serde_json from 1.0.104 to 1.0.105
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.104 to 1.0.105.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.104...v1.0.105)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-03 00:01:58 +00:00
link2xt
ec56134583 Remove winreg entry from deny.toml 2023-09-02 23:01:00 +00:00
dependabot[bot]
d8bf1c1691 chore(cargo): bump reqwest from 0.11.18 to 0.11.20
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.11.18 to 0.11.20.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.11.18...v0.11.20)

---
updated-dependencies:
- dependency-name: reqwest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 23:01:00 +00:00
dependabot[bot]
8ac1754e18 chore(cargo): bump tempfile from 3.7.0 to 3.8.0
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.7.0 to 3.8.0.
- [Changelog](https://github.com/Stebalien/tempfile/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Stebalien/tempfile/compare/v3.7.0...v3.8.0)

---
updated-dependencies:
- dependency-name: tempfile
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 22:05:42 +00:00
dependabot[bot]
e1f1143919 chore(cargo): bump quote from 1.0.32 to 1.0.33
Bumps [quote](https://github.com/dtolnay/quote) from 1.0.32 to 1.0.33.
- [Release notes](https://github.com/dtolnay/quote/releases)
- [Commits](https://github.com/dtolnay/quote/compare/1.0.32...1.0.33)

---
updated-dependencies:
- dependency-name: quote
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 22:05:08 +00:00
dependabot[bot]
d9e38289c4 chore(cargo): bump image from 0.24.6 to 0.24.7
Bumps [image](https://github.com/image-rs/image) from 0.24.6 to 0.24.7.
- [Changelog](https://github.com/image-rs/image/blob/master/CHANGES.md)
- [Commits](https://github.com/image-rs/image/compare/v0.24.6...v0.24.7)

---
updated-dependencies:
- dependency-name: image
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 21:57:51 +00:00
dependabot[bot]
486050d0b8 chore(cargo): bump backtrace from 0.3.68 to 0.3.69
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.68 to 0.3.69.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.68...0.3.69)

---
updated-dependencies:
- dependency-name: backtrace
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 19:16:16 +00:00
dependabot[bot]
828c90ac3d chore(cargo): bump tokio from 1.29.1 to 1.32.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.29.1 to 1.32.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.29.1...tokio-1.32.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 19:14:54 +00:00
dependabot[bot]
ab09ecce7e chore(cargo): bump schemars from 0.8.12 to 0.8.13
Bumps [schemars](https://github.com/GREsau/schemars) from 0.8.12 to 0.8.13.
- [Release notes](https://github.com/GREsau/schemars/releases)
- [Changelog](https://github.com/GREsau/schemars/blob/master/CHANGELOG.md)
- [Commits](https://github.com/GREsau/schemars/compare/v0.8.12...v0.8.13)

---
updated-dependencies:
- dependency-name: schemars
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 18:26:24 +00:00
dependabot[bot]
aebad2eb10 chore(cargo): bump url from 2.4.0 to 2.4.1
Bumps [url](https://github.com/servo/rust-url) from 2.4.0 to 2.4.1.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.4.0...v2.4.1)

---
updated-dependencies:
- dependency-name: url
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:45:25 +00:00
dependabot[bot]
2a39a85d9e chore(cargo): bump thiserror from 1.0.44 to 1.0.47
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.44 to 1.0.47.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.44...1.0.47)

---
updated-dependencies:
- dependency-name: thiserror
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:44:37 +00:00
dependabot[bot]
cb0270baa7 chore(cargo): bump anyhow from 1.0.72 to 1.0.75
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.72 to 1.0.75.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.72...1.0.75)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:44:11 +00:00
dependabot[bot]
99302c9598 chore(cargo): bump base64 from 0.21.2 to 0.21.3
Bumps [base64](https://github.com/marshallpierce/rust-base64) from 0.21.2 to 0.21.3.
- [Changelog](https://github.com/marshallpierce/rust-base64/blob/master/RELEASE-NOTES.md)
- [Commits](https://github.com/marshallpierce/rust-base64/compare/v0.21.2...v0.21.3)

---
updated-dependencies:
- dependency-name: base64
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:44:02 +00:00
dependabot[bot]
88ae653760 chore(cargo): bump chrono from 0.4.26 to 0.4.28
Bumps [chrono](https://github.com/chronotope/chrono) from 0.4.26 to 0.4.28.
- [Release notes](https://github.com/chronotope/chrono/releases)
- [Changelog](https://github.com/chronotope/chrono/blob/main/CHANGELOG.md)
- [Commits](https://github.com/chronotope/chrono/compare/v0.4.26...v0.4.28)

---
updated-dependencies:
- dependency-name: chrono
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:43:13 +00:00
dependabot[bot]
6881f9d70f chore(cargo): bump syn from 2.0.28 to 2.0.29
Bumps [syn](https://github.com/dtolnay/syn) from 2.0.28 to 2.0.29.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/2.0.28...2.0.29)

---
updated-dependencies:
- dependency-name: syn
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-02 17:42:09 +00:00
dependabot[bot]
60ddbe5729 chore(cargo): bump strum_macros from 0.25.1 to 0.25.2
Bumps [strum_macros](https://github.com/Peternator7/strum) from 0.25.1 to 0.25.2.
- [Changelog](https://github.com/Peternator7/strum/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Peternator7/strum/commits)

---
updated-dependencies:
- dependency-name: strum_macros
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-01 21:09:22 +00:00
iequidoo
5e5e557c8b Merge branch 'stable'
7c7cd9cc80 is a backport from `master`, so skip it.
2023-09-01 13:23:10 -03:00
iequidoo
bc8023644c Merge commit '7c7cd9cc8084f0e425b1919b84d5e79ed150d16b~' into HEAD
Merge `stable` up to the mentioned commit.
2023-09-01 13:14:44 -03:00
iequidoo
7c7cd9cc80 fix: Return from dc_get_chatlist(DC_GCL_FOR_FORWARDING) only chats where we can send (#4616)
I.e. exclude from the list the following chats as well:
- Read-only mailing lists.
- Chats we're not a member of.

But as for ProtectionBroken chats, we return them, as that may happen to a verified chat at any
time. It may be confusing if a chat that is normally in the list disappears suddenly. The UI need to
deal with that case anyway.

(cherry picked from commit 83ef25e7de)
2023-09-01 12:28:41 -03:00
iequidoo
83ef25e7de fix: Return from dc_get_chatlist(DC_GCL_FOR_FORWARDING) only chats where we can send (#4616)
I.e. exclude from the list the following chats as well:
- Read-only mailing lists.
- Chats we're not a member of.

But as for ProtectionBroken chats, we return them, as that may happen to a verified chat at any
time. It may be confusing if a chat that is normally in the list disappears suddenly. The UI need to
deal with that case anyway.
2023-09-01 10:26:22 -03:00
iequidoo
47d465e6e4 fix: Save mime headers for messages not signed with a known key (#4557)
If a message is unsigned or signed with an unknown key, `MimeMessage::was_encrypted()` returns
false. So, it mustn't be checked when deciding whether to look into
`MimeMessage::decoded_data`. Looking through git history one can see that it's just a wrong check
left in the code for historical reasons.
2023-08-31 14:07:12 -03:00
link2xt
03d3e0578f refactor(deltachat-rpc-client): drop support for keyword arguments
All Rust methods have positional arguments and it is not going to change.
2023-08-31 00:46:04 +00:00
iequidoo
440a442f30 fix: Allow membership changes by a MUA if we're not in the group (#4624)
Other MUAs don't set add/remove headers, so the only way for them to re-add us to the group is to
add us to To/CC/wherever. Previously it worked only for other members that are still in the group so
that they properly handled our re-addition, but we didn't.
2023-08-29 22:19:15 -03:00
link2xt
1da52d7d1d refactor: use split_once() instead of regexp in heuristically_parse_ndn
Reduce dependency on the huge `regex` crate.
2023-08-29 18:41:07 +00:00
link2xt
9a7d1faf75 Merge tag 'v1.120.0' 2023-08-28 11:55:53 +00:00
link2xt
4d74f625d3 chore(release): prepare for 1.120.0 2023-08-28 11:54:38 +00:00
link2xt
0a94fbc735 fix: update async-imap to 0.9.1 to fix memory leak 2023-08-28 09:04:28 +00:00
link2xt
9ef34890fa chore: fix beta clippy warnings 2023-08-28 04:09:52 +00:00
iequidoo
3e07f2c173 fix: prepare_msg_blob(): If cannot recode image, don't use it if it has Exif
We mustn't send images with Exif as it can leak metadata such as location, camera model, etc.
2023-08-27 23:16:19 -03:00
iequidoo
ee28298d7f fix: W/a sending images sent as stickers on some platforms (#4611)
Check if a sticker has at least one fully transparent corner and otherwise change the Sticker type
to Image. This would fix both Android and iOS at the same time and prevent similar bug on future
platforms that may get this bug like Ubuntu Touch.
2023-08-27 23:16:19 -03:00
link2xt
e59c4ee858 Merge branch 'stable' 2023-08-27 22:18:36 +00:00
link2xt
62aed13880 refactor: hide pgp module from public API 2023-08-27 22:03:00 +00:00
link2xt
bffe934acc refactor: hide accounts.rs constants from public API 2023-08-27 22:03:00 +00:00
link2xt
a520f0268f chore: rustfmt 2023-08-26 18:15:11 +00:00
link2xt
5e3b1fa540 Merge branch 'stable' 2023-08-26 18:12:13 +00:00
iequidoo
95f29f7b63 fix: receive_imf: Set protection only for Chattype::Single (#4597)
Also don't set protection to ProtectionBroken if it already is.

Co-authored-by: Hocuri <hocuri@gmx.de>
2023-08-26 13:19:48 -03:00
link2xt
87ffcaf03e build: update to Rust 1.72.0 2023-08-25 23:04:47 +00:00
link2xt
2635146328 build: update to Zig 0.11.0 2023-08-25 21:20:11 +00:00
link2xt
d727d85f6d chore(python): fix ruff 0.0.286 warnings 2023-08-25 20:57:44 +00:00
link2xt
20513475ef Merge branch 'stable' 2023-08-25 01:59:04 +00:00
link2xt
81a7af10c7 chore(python): fix lint errors 2023-08-25 01:14:24 +00:00
link2xt
4a6e94f8ab build(deny): ignore RUSTSEC-2023-0052 2023-08-25 01:04:02 +00:00
link2xt
146fe50e20 build(cargo-deny): ignore RUSTSEC-2022-0093
It is an API issue that can only be fixed in rPGP and iroh upstream.
2023-08-25 01:03:56 +00:00
link2xt
9bf2850fb1 ci: run on push to stable branch 2023-08-25 00:58:14 +00:00
iequidoo
ba2c36548e fix: Delete messages from SMTP queue only on user demand (#4579)
I.e. from delete_msgs(). Otherwise messages must not be deleted from there, e.g. if a message is
ephemeral, but a network outage lasts longer than the ephemeral message timer, the message still
must be sent upon a successful reconnection.
2023-08-24 23:24:24 +00:00
link2xt
3b806320ec Merge branch 'stable' 2023-08-24 22:25:02 +00:00
Simon Laux
d07c743cdc api(jsonrpc): add resend_messages 2023-08-24 22:04:47 +00:00
dependabot[bot]
c857d6e1bd Merge pull request #4591 from deltachat/dependabot/cargo/sanitize-filename-0.5.0 2023-08-24 20:01:21 +00:00
dependabot[bot]
94cd9a713f chore(cargo): bump sanitize-filename from 0.4.0 to 0.5.0
Bumps [sanitize-filename](https://github.com/kardeiz/sanitize-filename) from 0.4.0 to 0.5.0.
- [Commits](https://github.com/kardeiz/sanitize-filename/commits)

---
updated-dependencies:
- dependency-name: sanitize-filename
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-24 18:42:54 +00:00
link2xt
7676473ebd fix: do not mark non-verified group chats as verified when using securejoin
Only mark the chat is verified if 1:1 verified chats are enabled
and securejoin targets a 1:1 chat.
2023-08-24 18:39:56 +00:00
link2xt
8c778b3f5c test: extend test_qr_join_chat to check that the group is not verified 2023-08-24 18:39:56 +00:00
iequidoo
a66f8bd9fc fix: Delete messages from SMTP queue only on user demand (#4579)
I.e. from delete_msgs(). Otherwise messages must not be deleted from there, e.g. if a message is
ephemeral, but a network outage lasts longer than the ephemeral message timer, the message still
must be sent upon a successful reconnection.
2023-08-24 13:39:22 -03:00
iequidoo
95b2a15930 fix: Sort old incoming messages below all outgoing ones (#4621)
If the Inbox is fetched before the Sentbox (as done currently), messages from the Sentbox will
correctly mingle with the Inbox messages in the end. So, this commit changes message ordering only
if we already have processed outgoing messages, e.g. if we just sent them in the chat as described
in #4621. Otherwise new incoming messages are displayed somewhere in the middle of the chat which
doesn't look usable.
2023-08-24 13:22:26 -03:00
iequidoo
0179ec2da9 fix: receive_imf: Update peerstate from db after handling Securejoin handshake (#4600)
Otherwise has_verified_encryption() would check a stale Peerstate object.
2023-08-24 01:29:25 +00:00
iequidoo
8f2313bb2a test: test_openrpc_command_line: Check that deltachat-rpc-server exists with 0 2023-08-23 19:30:14 +00:00
link2xt
488a3d1118 build(deny): ignore RUSTSEC-2023-0052 2023-08-23 19:30:14 +00:00
link2xt
9094df7bc7 build(python): pin sphinx to 7.1.2 2023-08-23 19:30:14 +00:00
link2xt
16aad3fa67 build(cargo-deny): ignore RUSTSEC-2022-0093
It is an API issue that can only be fixed in rPGP and iroh upstream.
2023-08-17 12:20:58 +00:00
iequidoo
3b47c3f21d ci: Run Rust tests with RUST_BACKTRACE set 2023-08-15 14:24:02 -03:00
link2xt
987ce58926 chore(python): fix lint errors 2023-08-11 17:06:15 +00:00
iequidoo
20c88743df test: W/a message reordering in test_reaction_to_partially_fetched_msg() 2023-08-08 21:02:41 -03:00
dependabot[bot]
03395b95cb chore(cargo): bump quick-xml from 0.29.0 to 0.30.0
Bumps [quick-xml](https://github.com/tafia/quick-xml) from 0.29.0 to 0.30.0.
- [Release notes](https://github.com/tafia/quick-xml/releases)
- [Changelog](https://github.com/tafia/quick-xml/blob/master/Changelog.md)
- [Commits](https://github.com/tafia/quick-xml/compare/v0.29.0...v0.30.0)

---
updated-dependencies:
- dependency-name: quick-xml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-08 21:02:41 -03:00
Hocuri
53f04a134a test: Don't accidentally accept that a chat protection is broken (#4550) 2023-08-08 11:35:38 +02:00
Hocuri
885f26ea8c test: Directly unwrap in TestContext::get_chat() (#4614)
Directly unwrap in TestContext::get_chat()

Turns out that all usages of get_chat() directly unwrapped, because in a
test it doesn't make sense to handle the error of there being no chat.
2023-08-08 11:34:52 +02:00
link2xt
3ab181fdf8 build: update to Zig 0.11.0 2023-08-06 19:44:48 +00:00
link2xt
d70c1d48b5 chore(release) prepare for 1.119.1 2023-08-06 16:49:06 +00:00
link2xt
a8e0cb9b5a fix: update xattr from 1.0.0 to 1.0.1 to fix UnsupportedPlatformError import
See the folowing PRs on the `xattr` repository:
- https://github.com/Stebalien/xattr/pull/34
- https://github.com/Stebalien/xattr/pull/38
2023-08-06 16:45:58 +00:00
link2xt
6ea9a8988b test(webxdc): ensure unknown WebXDC update properties do not result in an error 2023-08-06 16:27:29 +00:00
iequidoo
45e35b3571 feat: Guess message viewtype from "application/octet-stream" attachment extension (#4378) 2023-08-05 16:34:06 -03:00
link2xt
e12044e6af api!(deltachat-jsonrpc): use kind as a tag for all union types 2023-08-03 23:46:24 +00:00
link2xt
954067eb6d Merge tag 'v1.119.0' 2023-08-03 17:05:00 +00:00
link2xt
e43f9066d8 chore(release): prepare for 1.119.0 2023-08-03 17:03:26 +00:00
link2xt
aecbebd566 docs: improve JSON-RPC API documentation 2023-08-03 16:06:36 +00:00
link2xt
3111bcde5e refactor: flatten imports in deltachat-jsonrpc 2023-08-03 15:58:48 +00:00
link2xt
e6cffd537e refactor: remove Chattype::Undefined 2023-08-02 17:02:28 +00:00
link2xt
70000d9ebb build: increase MSRV to 1.67.0
This is required by time v0.3.24
2023-08-02 03:27:21 +00:00
link2xt
d95843b0bf chore(deps): update dependencies 2023-08-02 03:23:19 +00:00
link2xt
13e766bc37 feat(deltachat-rpc-server): add --openrpc option 2023-08-01 18:27:02 +00:00
link2xt
c34edc582e test: test that get_system_info() works over RPC backup import 2023-08-01 01:05:06 +00:00
link2xt
8eee389c09 refactor: use SQL transaction in MsgId.delete_from_db() 2023-07-31 20:01:35 +00:00
link2xt
8ed6d4d709 api!: make MsgId.delete_from_db() private
Use `delete_msgs()` if you are using the Delta Chat core
as a library and want to delete a message.
2023-07-31 20:01:35 +00:00
Hocuri
60bacbec47 feat: Don't show a contact as verified if their key changed since the verification (#4574)
Don't show a contact as verified if their key changed in the meantime

If a contact's key changed since the verification, then it's very
unlikely that they still have the old, verified key. So, don't show them
as verified anymore.

This also means that you can't add a contact like this to a verified
group, which is good.

The documentation actually already described this (new) behavior:

```rust
/// and if the key has not changed since this verification.
```

so, this adapts the code to the documentation.
2023-07-31 18:59:45 +02:00
link2xt
af013559de refactor: hide DcSecretKey trait from the API 2023-07-29 18:10:25 +00:00
link2xt
b784415c57 refactor: move dc_preconfigure_keypair() implementation into deltachat crate
This allows to hide `DcKey` trait from public API.
2023-07-29 18:05:05 +00:00
link2xt
85739ba6ad refactor: make last_added_location_id an Option 2023-07-29 17:45:15 +00:00
B. Petersen
a02a593f47 fix example; this was changed some time ago, see https://docs.webxdc.org/spec.html#sendupdate 2023-07-29 05:08:54 +02:00
link2xt
bba6c8f15a fix: emit MsgsChanged event with correct chat id for replaced messages
Previously an event with DC_CHAT_ID_TRASH was emitted.
2023-07-28 21:51:08 +00:00
link2xt
67f28f501a Merge branch 'stable' 2023-07-27 19:40:01 +00:00
link2xt
9b9703a48e refactor: replace DcKey.load_self trait method with functions 2023-07-27 18:23:56 +00:00
link2xt
c55a3d3873 refactor: flatten and simplify imports 2023-07-27 17:47:30 +00:00
iequidoo
55aaec744a feat: Make dc_msg_get_filename() return the original attachment filename (#4309)
It can be used e.g. as a default in the file saving dialog. Also display the original filename in
the message info. For these purposes add Param::Filename in addition to Param::File and use it as an
attachment filename in sent emails.
2023-07-27 14:31:14 -03:00
iequidoo
f27d304f3b feat!: Add lockfile to account manager (#4310)
Opening the same account (context) from multiple processes is dangerous, can result in duplicate
downloads of the same message etc. Same for account manager, attempts to modify the same
accounts.toml even if done atomically with may result in corrupted files as atomic replacement
procedure does not expect that multiple processes may write to the same temporary file.

accounts.toml cannot be used as a lockfile because it is replaced during atomic update. Therefore, a
new file next to accounts.toml is needed to prevent starting second account manager in the same
directory.

But iOS needs to be able to open accounts from multiple processes at the same time. This is required
as the "share-to-DC extension" is a separate process by iOS design -- this process may or may not be
started while the main app is running. Accounts are not altered however by this extension, so let's
add to the `Accounts::new()` constructor an `rdwr` parameter which allows to read the accounts
config w/o locking the lockfile.
2023-07-26 16:02:25 -03:00
link2xt
2f24eddb7d fix: base64-encode webxdc updates
Webxdc update messages may contain
long lines that get hard-wrapped
and may corrupt JSON if the message
is not encrypted.

base64-encode the update part
to avoid hard wrapping.

This is not necessary for encrypted
messages, but does not introduce
size overhead as OpenPGP messages
are compressed.
2023-07-26 15:06:29 +00:00
link2xt
6d51d19f01 refactor(e2ee): do not return anything from ensure_secret_key_exists()
The return value was never used.
2023-07-26 11:19:08 +00:00
Hocuri
170968dfc2 Update README.md 2023-07-25 16:50:10 +02:00
link2xt
a33c91afa9 fix(webxdc): check if status update sender is the member of the correct chat 2023-07-24 22:53:30 +00:00
link2xt
f930576fd1 Merge branch 'stable' 2023-07-24 18:40:44 +00:00
link2xt
d52f2883cf feat(deltachat-rpc-client): add MSG_DELETED constant 2023-07-24 18:40:32 +00:00
link2xt
b872953bc5 fix(deltachat-jsonrpc): make MessageObject.text non-optional
This is already non-optional on the `deltachat` crate side
since <https://github.com/deltachat/deltachat-core-rust/pull/4517>
2023-07-24 18:36:56 +00:00
link2xt
d797de7a8d refactor: use slices and vectors instead of Keyring wrapper
This change removes all traces of dc_keyring_t,
which was a C implementation of dynamically sized array.
2023-07-24 18:05:38 +00:00
link2xt
acc7bb00c5 chore(deps): update rPGP 2023-07-24 16:14:16 +00:00
link2xt
8fb8a877be chore(deps): update dependencies 2023-07-24 14:06:09 +00:00
Hocuri
b96028cd87 api!(Rust): Remove unused function is_verified_ex() (#4551)
No one used it anymore, and all occurences I could find (on
GitHub)[https://github.com/search?q=%22is_verified_ex%22&type=code&p=1]
are either forks of deltachat-core-rust or of deltachat-core (which is
the old C core).
2023-07-24 12:19:13 +02:00
Hocuri
682e241edb fix: Fix info-message orderings of verified 1:1 chats (#4545)
Correctly handle messages with old timestamps for verified chats:

 * They must not be sorted over a protection-changed info message

 * If they change the protection, then they must not be sorted over existing other messages, because then the protection-changed info message would also be above these existing messages.


This PR fixes this:

 1. Even seen messages can't be sorted into already-noticed messages anymore. **This also changes DC's behavior in the absence of verified 1:1 chats**. Before this PR, messages that are marked as seen when they are downloaded will always be sorted by their timestamp, even if it's very old.

 2. protection-changed info messages are always sorted to the bottom.

    **Edit:**

 3. There is an exception to rule 1: Outgoing messages are still allowed to be sorted purely by their timestamp, and don't influence old messages. This is to the problem described at [*].


Together, these rules also make sure that the protection-changed info message is always right above the message causing the change.

[*] If we receive messages from two different folders, e.g. `Sent` and `Inbox`, then this will lead to wrong message ordering in many cases. I need to think about this more, or maybe someone else has an idea. One new idea that came to my mind is:

 * Always sort noticed messages under the newest info message (this PR sorts them under the newest noticed message, master sorts them purely by their sent timestamp)

 * Always sort unnoticed messages under the newest noticed message (that's the same behavior as in this PR and on master)

 * Always sort protection-changed info messages to the bottom (as in this PR)


However, after a talk with @link2xt we instead decided to add rule 3. (see above) because it seemed a little bit easier.
2023-07-24 12:16:32 +02:00
link2xt
c1cb6eef08 refactor: improve IMAP logs 2023-07-23 12:19:50 +00:00
Simon Laux
3a63628f1f update node constants
looks like this was fogotten when changing the chat protection stock strings
2023-07-23 09:26:01 +00:00
link2xt
3705616cd9 Merge branch 'stable' 2023-07-23 09:17:13 +00:00
B. Petersen
200b808c27 add tests for deletion of webxdc status-updates 2023-07-23 09:16:28 +00:00
B. Petersen
d572d960e5 delete old webxdc status updates during housekeeping 2023-07-23 09:16:28 +00:00
Simon Laux
b8fcb660ad cargo fmt 2023-07-23 02:29:42 +02:00
Simon Laux
5673294623 api(jsonrpc): add resend_messages 2023-07-23 02:29:42 +02:00
B. Petersen
7062bb0502 clarify transitive behaviour of dc_contact_is_verfified() 2023-07-22 20:58:05 +02:00
link2xt
5db75128ba fix: accept WebXDC updates in mailing lists 2023-07-22 01:30:52 +00:00
link2xt
fbd2fc8ead test: add test_webxdc_download_on_demand
The test checks that if webxdc update is too large to
download with the current `download_limit`,
it is applied afterwards when the user manually downloads the update message.
2023-07-21 21:23:44 +00:00
link2xt
bc73c16df7 chore: fix compiler warnings 2023-07-21 09:33:59 +00:00
link2xt
659cffe0cc ci: remove comment about python from rust tests 2023-07-19 13:43:20 +00:00
link2xt
a1663a98e0 build: use Rust 1.71.0 and increase MSRV to 1.66.0
Rust 1.66 is required by constant_time_eq 0.3.0.
2023-07-19 13:41:31 +00:00
link2xt
3de1dbc9e4 chore(deps): update dependencies 2023-07-19 13:26:47 +00:00
link2xt
6d37e8601e Merge branch 'stable' 2023-07-17 17:11:38 +00:00
link2xt
0a50bad555 fix(deltachat-rpc-server): update tokio-tar to fix backup import
tokio-tar 0.3.0 prints message "create_dir_all ..." to stdout during import.
tokio-tar 0.3.1 has removed this debug output which broke stdio JSON-RPC protocol.
2023-07-17 17:07:13 +00:00
link2xt
82c0058129 test: add basic import/export test for async python 2023-07-17 17:07:13 +00:00
link2xt
1bd307a26a api(deltachat-rpc-client): add Account.{import,export}_backup methods 2023-07-17 17:07:13 +00:00
link2xt
740f43a2d6 fix: do not resync IMAP after initial configuration
If there was no previous `configured_addr`,
then there is no need to run IMAP resync.
2023-07-17 16:38:09 +00:00
Hocuri
d762753103 fix: Allow to save a draft if the verification is broken (#4542)
If the verification is broken, `can_send()` is false.

But if the user was typing a message right when a verification-breaking message came in, the UI still needs to be able to save it as a draft.

Steps to reproduce the bug:
  - Set a draft
  - Your chat partner breaks verification
  - Go back to the chats list
  - Go to the chat again
  - Accept the breakage
  - Expected: The draft is still there
  - Bug behavior: The draft is gone
2023-07-16 12:04:43 +02:00
link2xt
a020d5ccce Merge branch 'stable' 2023-07-14 11:23:43 +00:00
link2xt
c14f45a8f5 fix(imap): avoid IMAP move loops when DeltaChat folder is aliased
Some Dovecot servers are configured
to alias "INBOX.DeltaChat" and "DeltaChat" to the same folder.
In this case Delta Chat moves new emails from "INBOX"
to "DeltaChat", but then discovers the same mail in "INBOX.DeltaChat"
and tries to move it to "DeltaChat" again.
Each time a MOVE command is issued to move the message
from "INBOX.DeltaChat" to "DeltaChat", the message gets a new UID.

To prevent such IMAP move loop between aliased folders,
we do not move the message if we have already seen it on IMAP,
i.e. we have its Message-ID in the `imap` table.
Note that we do not use `rfc724_mid_exists`,
because it checks the `msgs` table and would consider
BCC-self messages seen even before we see them in the Inbox,
preventing their move to the DeltaChat folder.

Duplicate messages and messages without Message-IDs
are not moved anymore, but this is better
than having an infinite move loop.
2023-07-14 11:21:31 +00:00
link2xt
8269116dba chore(python): fix ruff warnings 2023-07-12 19:49:12 +00:00
Hocuri
1e28ea9bb0 fix: Don't create 1:1 chat as protected for contact who doesn't prefer to encrypt (#4538) 2023-07-11 17:39:59 +00:00
Hocuri
17f2d33731 test: Remove unnecessary inner_set_protection() call (#4539)
1:1 chats are automatically created as protected if the contact is
verified, there is no need to explicitly do this.

Plus, by removing this call, the test also tests that automatically
creating 1:1 chats as protected works.
2023-07-11 19:15:23 +02:00
link2xt
db941ccf88 fix: return valid MsgId from receive_imf() when the message is replaced
receive_imf() calls add_parts()
which INSERTs or UPDATEs the message using UPSERT [1].
It then uses last_insert_rowid() to get
the ID of the inserted message.
However, it is incorrect to use last_insert_rowid()
if an UPDATE was executed instead of INSERT.
The solution is to use `RETURNING id` clause
to make the UPSERT statement return message ID in any case [2].

The fix is tested in test_webxdc_update_for_not_downloaded_instance()
and with a debug_assert!.

[1] https://www.sqlite.org/lang_UPSERT.html
[2] https://sqlite.org/forum/forumpost/9ce3bc1c4a85c15f
2023-07-11 08:43:01 +00:00
link2xt
a464cbdfe6 chore: rustfmt 2023-07-11 00:03:57 +00:00
link2xt
976797d4cf build: remove examples/simple.rs
When `cargo test` is executed,
all examples are built by default
to ensure that they can be compiled.

This is a documented and expected behaviour,
even though it was previously reported as a bug:
<https://github.com/rust-lang/cargo/issues/6675>

In particular, `examples/simple.rs` is built into
a 67M binary `target/debug/examples/simple`.
This is unnecessary to do so every time
you change a line in the `deltachat` crate
and want to rerun the tests.

Workaround is to run `cargo test --tests`,
but it is easy to forget and is not discoverable
unless you read the "Target Selection" section of `cargo help test`.

We have a maintained example at https://github.com/deltachat-bot/echo,
so there is no need for an example in the core repository.
2023-07-10 21:49:31 +00:00
link2xt
31e3169433 chore: nightly clippy fixes 2023-07-10 11:38:46 +02:00
link2xt
d2b15cb629 docs: document how logs and error messages should be formatted 2023-07-09 16:18:18 +00:00
Hocuri
9cd000c4f2 feat: Verified 1:1 chats (#4315)
Implement #4188

BREAKING CHANGE: Remove unused DC_STR_PROTECTION_(EN)ABLED* strings
BREAKING CHANGE: Remove unused dc_set_chat_protection()
2023-07-09 14:06:45 +02:00
link2xt
ea4a0530b8 docs: update default value for show_emails in dc_set_config() documentation 2023-07-08 09:25:09 +02:00
link2xt
243c035b03 chore: spellcheck 2023-07-07 21:56:59 +00:00
link2xt
9d3b2d4844 chore(release): prepare for 1.118.0 2023-07-07 17:01:03 +00:00
link2xt
c312280ab3 build(git-cliff): do not fail if commit.footers is undefined 2023-07-07 16:41:10 +00:00
link2xt
572b99a2e1 Rewrite member added/removed messages even if the change is not allowed
PR https://github.com/deltachat/deltachat-core-rust/pull/4529
2023-07-06 13:47:56 +00:00
link2xt
3992b5a063 refactor: move handle_mdn and handle_ndn to mimeparser and make them private
Previously handle_mdn was erroneously exposed in the public API.
2023-07-06 12:34:49 +00:00
link2xt
b97cb4b55e chore(cargo): update Cargo.lock 2023-07-06 12:33:58 +00:00
link2xt
64c218f1ea fix: rewrite "member added" message even if change is not allowed 2023-07-06 01:36:42 +00:00
link2xt
deed790950 test: test that "member added" message is rewritten even if self is not in chat 2023-07-06 01:36:23 +00:00
link2xt
b33ae3cd0f fix: rewrite "member removed" message even if change is not allowed 2023-07-06 01:36:23 +00:00
link2xt
9480699362 test: test that "member removed" message is rewritten if self is not in chat 2023-07-06 01:36:08 +00:00
link2xt
94c190e844 fix: use different member added/removal messages locally and on the network
This commit adds new stock strings
"I added member ...",
"I removed member ..." and
"I left the group" that are sent over the network
and are visible in classic MUAs like Thunderbird.

Member name in these messages uses authname
instead of the display name,
so the name set locally does not get leaked when
a member is added or removed.
2023-07-05 16:16:30 +00:00
link2xt
578e47666f api!: replace message::get_msg_info() with MsgId.get_info() 2023-07-05 14:22:37 +00:00
link2xt
7eeced50d1 chore(cargo): bump backtrace from 0.3.67 to 0.3.68 2023-07-04 19:19:27 +00:00
link2xt
46e127ad27 chore(cargo): bump hermit-abi from 0.3.1 to 0.3.2
0.3.1 is yanked
2023-07-04 16:56:19 +00:00
link2xt
4891849e28 chore: add LICENSE file to deltachat-rpc-client
This gets packaged into the wheel when you run `python -m build`.
2023-07-03 23:01:46 +00:00
link2xt
e0dd83d538 chore: update MPL 2.0 license text
New text was downloaded from https://www.mozilla.org/en-US/MPL/,
specifically https://www.mozilla.org/media/MPL/2.0/index.f75d2927d3c1.txt

The difference is that the URL is changed from http:// to https://
2023-07-04 00:52:31 +02:00
link2xt
aac8bb950c chore(python): add "Topic :: Communications :: Chat" classifier 2023-07-03 22:49:14 +00:00
link2xt
bf21796bc0 chore(python): change bindings status to production/stable 2023-07-03 22:48:51 +00:00
link2xt
9cbf413064 chore(deltachat-rpc-client): add Trove classifiers 2023-07-03 21:22:10 +00:00
dependabot[bot]
1b57eb4d8d chore(cargo): bump serde from 1.0.164 to 1.0.166
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.164 to 1.0.166.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.164...v1.0.166)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 20:31:10 +00:00
link2xt
5152e702bd chore(cargo): bump num-derive from 0.3.3 to 0.4.0 2023-07-03 19:49:58 +00:00
link2xt
c80f1a1997 chore(cargo): bump toml from 0.7.4 to 0.7.5 2023-07-03 19:41:31 +00:00
link2xt
88759c815b refactor(python): flatten the API of deltachat module 2023-07-03 16:19:31 +00:00
link2xt
9c68fac4b6 api!: make Message.text non-optional
Message.set_text() and Message.get_text() are modified accordingly
to accept String and return String.

Messages which previously contained None text
are now represented as messages with empty text.
Use Message.set_text("".to_string())
instead of Message.set_text(None).
2023-07-03 15:36:32 +00:00
dependabot[bot]
8e17e400b3 chore(cargo): bump uuid from 1.3.3 to 1.4.0
Bumps [uuid](https://github.com/uuid-rs/uuid) from 1.3.3 to 1.4.0.
- [Release notes](https://github.com/uuid-rs/uuid/releases)
- [Commits](https://github.com/uuid-rs/uuid/compare/1.3.3...1.4.0)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 00:20:16 +00:00
dependabot[bot]
dae3857db8 chore(cargo): bump syn from 2.0.18 to 2.0.23
Bumps [syn](https://github.com/dtolnay/syn) from 2.0.18 to 2.0.23.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/2.0.18...2.0.23)

---
updated-dependencies:
- dependency-name: syn
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 23:45:42 +00:00
dependabot[bot]
695f71e124 chore(cargo): bump strum from 0.24.1 to 0.25.0
Bumps [strum](https://github.com/Peternator7/strum) from 0.24.1 to 0.25.0.
- [Changelog](https://github.com/Peternator7/strum/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Peternator7/strum/commits)

---
updated-dependencies:
- dependency-name: strum
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 23:45:32 +00:00
link2xt
2d30afd212 fix: do not run simplify() on dehtml() output
simplify() is written to process incoming plaintext messages
and extract footers and quotes from them.
Incoming messages contain various quote styles
and simplify() implements heuristics to detects them.

If dehtml() output is processed by simplify(),
simplify() heuristics may erroneously detect
footers and quotes in produced plaintext.

dehtml() should directly detect quotes
instead of converting them to plaintext quotes
for parsing with simplify().
2023-07-02 23:12:13 +00:00
link2xt
5fe94e8bce docs(dehtml): document AddText variants 2023-07-02 23:12:13 +00:00
link2xt
1351f71632 fix(remove_contact_from_chat): do not emit event if the contact was not removed 2023-07-02 23:00:49 +00:00
link2xt
d42322b38b fix(remove_contact_from_chat): bubble up chat loading errors 2023-07-02 23:00:49 +00:00
link2xt
ce6876c418 fix(remove_contact_from_chat): do not ignore database errors when loading the contact 2023-07-02 23:00:49 +00:00
link2xt
2a6b7d9766 api(contact): add Contact::get_by_id_optional() API 2023-07-02 23:00:49 +00:00
link2xt
fa1924da2b api!(contact): remove Contact::load_from_db() in favor of Contact::get_by_id() 2023-07-02 23:00:49 +00:00
link2xt
d5214eb192 refactor: check if the contact is blocked with a dedicated SQL query
Avoid loading unnecessary fields from the database.
2023-07-02 23:00:49 +00:00
dependabot[bot]
c47324d671 chore(cargo): bump regex from 1.8.3 to 1.8.4
Bumps [regex](https://github.com/rust-lang/regex) from 1.8.3 to 1.8.4.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.8.3...1.8.4)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 21:49:32 +00:00
dependabot[bot]
3f8ec5ec56 chore(cargo): bump testdir from 0.7.3 to 0.8.0
Bumps [testdir](https://github.com/flub/testdir) from 0.7.3 to 0.8.0.
- [Changelog](https://github.com/flub/testdir/blob/main/CHANGELOG.md)
- [Commits](https://github.com/flub/testdir/compare/v0.7.3...v0.8.0)

---
updated-dependencies:
- dependency-name: testdir
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 21:49:23 +00:00
dependabot[bot]
fab504b54c chore(cargo): bump url from 2.3.1 to 2.4.0
Bumps [url](https://github.com/servo/rust-url) from 2.3.1 to 2.4.0.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.3.1...v2.4.0)

---
updated-dependencies:
- dependency-name: url
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 20:25:59 +00:00
dependabot[bot]
dd32430ade chore(cargo): bump strum_macros from 0.24.3 to 0.25.0
Bumps [strum_macros](https://github.com/Peternator7/strum) from 0.24.3 to 0.25.0.
- [Changelog](https://github.com/Peternator7/strum/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Peternator7/strum/commits)

---
updated-dependencies:
- dependency-name: strum_macros
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 20:23:28 +00:00
link2xt
eb943625a6 chore(cargo): bump num_cpus from 1.15.0 to 1.16.0 2023-07-02 20:19:40 +00:00
dependabot[bot]
32ac4a01ca chore(cargo): bump tempfile from 3.5.0 to 3.6.0
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.5.0 to 3.6.0.
- [Changelog](https://github.com/Stebalien/tempfile/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Stebalien/tempfile/compare/v3.5.0...v3.6.0)

---
updated-dependencies:
- dependency-name: tempfile
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 19:36:50 +00:00
dependabot[bot]
f01a9d7d5c chore(cargo): bump rustyline from 11.0.0 to 12.0.0
Bumps [rustyline](https://github.com/kkawakam/rustyline) from 11.0.0 to 12.0.0.
- [Release notes](https://github.com/kkawakam/rustyline/releases)
- [Changelog](https://github.com/kkawakam/rustyline/blob/master/History.md)
- [Commits](https://github.com/kkawakam/rustyline/compare/v11.0.0...v12.0.0)

---
updated-dependencies:
- dependency-name: rustyline
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 18:33:04 +00:00
dependabot[bot]
a5db7104c2 chore(cargo): bump quote from 1.0.28 to 1.0.29
Bumps [quote](https://github.com/dtolnay/quote) from 1.0.28 to 1.0.29.
- [Release notes](https://github.com/dtolnay/quote/releases)
- [Commits](https://github.com/dtolnay/quote/compare/1.0.28...1.0.29)

---
updated-dependencies:
- dependency-name: quote
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 18:03:20 +00:00
dependabot[bot]
18aeb14003 chore(cargo): bump quick-xml from 0.28.2 to 0.29.0
Bumps [quick-xml](https://github.com/tafia/quick-xml) from 0.28.2 to 0.29.0.
- [Release notes](https://github.com/tafia/quick-xml/releases)
- [Changelog](https://github.com/tafia/quick-xml/blob/master/Changelog.md)
- [Commits](https://github.com/tafia/quick-xml/compare/v0.28.2...v0.29.0)

---
updated-dependencies:
- dependency-name: quick-xml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 18:02:37 +00:00
dependabot[bot]
4ad2d6e340 chore(cargo): bump sha2 from 0.10.6 to 0.10.7
Bumps [sha2](https://github.com/RustCrypto/hashes) from 0.10.6 to 0.10.7.
- [Commits](https://github.com/RustCrypto/hashes/compare/sha2-v0.10.6...sha2-v0.10.7)

---
updated-dependencies:
- dependency-name: sha2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 17:40:20 +00:00
dependabot[bot]
ce9cd54993 chore(cargo): bump serde_json from 1.0.96 to 1.0.99
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.96 to 1.0.99.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.96...v1.0.99)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 15:37:55 +00:00
dependabot[bot]
23f540f9f9 chore(cargo): bump serde from 1.0.163 to 1.0.164
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.163 to 1.0.164.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.163...v1.0.164)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 15:37:23 +00:00
dependabot[bot]
f994b2d8e4 chore(cargo): bump log from 0.4.18 to 0.4.19
Bumps [log](https://github.com/rust-lang/log) from 0.4.18 to 0.4.19.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.18...0.4.19)

---
updated-dependencies:
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 15:37:05 +00:00
dependabot[bot]
6e42b85a36 Merge pull request #4495 from deltachat/dependabot/cargo/tokio-1.29.1 2023-07-02 04:17:26 +00:00
link2xt
d69e42377d chore(deps): update human-panic from 1.1.4 to 1.1.5 2023-07-02 01:20:35 +00:00
link2xt
de9330b52f chore(deps): update libc from 0.2.146 to 0.2.147 2023-07-02 01:19:13 +00:00
dependabot[bot]
01d1c4c04b chore(cargo): bump tokio from 1.29.0 to 1.29.1
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.29.0 to 1.29.1.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.29.0...tokio-1.29.1)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-02 01:18:16 +00:00
link2xt
7d98978269 chore: rustfmt 2023-07-02 01:17:12 +00:00
link2xt
5024f48609 refactor: add error context to Message::load_from_db() 2023-07-01 19:40:23 +00:00
link2xt
e975568122 docs: fix a typo in get_for_contact documentation 2023-07-01 19:39:50 +00:00
link2xt
1f71c69325 fix: update tokio to 1.29.0
This fixes panic after sending 29 offline messages.
2023-06-28 09:11:57 +00:00
Hocuri
b80ec8507c test: reproduce tokio panic 2023-06-28 08:40:23 +00:00
link2xt
3a3f3542d9 chore: remove libm entry from deny.toml 2023-06-27 14:34:26 +00:00
link2xt
657c5fa947 chore(deps): update iana-time-zone-haiku to 0.1.2
This removes `cxx` dependency.
2023-06-27 14:33:34 +00:00
link2xt
7d0b25c209 chore(deps): update ed25519-dalek 2023-06-27 14:30:27 +00:00
link2xt
8d26303cad refactor(simplify): remove local variable empty_body 2023-06-25 12:55:21 +00:00
Simon Laux
0d8a76593a fix: make avatar image work on more platforms (use xlink:href)
Without it delta touch (qt) can not render the avatar image
and also inkscape does not show it either.
2023-06-22 15:42:08 +00:00
dependabot[bot]
7b49fb2eb6 chore(deps): bump openssl from 0.10.48 to 0.10.55 in /fuzz
Bumps [openssl](https://github.com/sfackler/rust-openssl) from 0.10.48 to 0.10.55.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.48...openssl-v0.10.55)

---
updated-dependencies:
- dependency-name: openssl
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-22 15:32:38 +00:00
link2xt
efa37dd283 fix: preserve indentation when converting plaintext to HTML 2023-06-22 13:24:40 +00:00
link2xt
323e44da04 test: make plaintext to HTML conversion tests non-async 2023-06-22 13:24:40 +00:00
link2xt
70efd0f10a refactor: use with statement with multiple contexts
Otherwise `ruff` check SIM117 fails.
2023-06-21 00:30:48 +00:00
link2xt
fcec81b4c1 chore(cargo): update openssl to 0.10.55
This fixes https://rustsec.org/advisories/RUSTSEC-2023-0044
2023-06-20 23:37:41 +00:00
link2xt
dd806b2d88 test: add make-python-testenv.sh script
This scripts makes it easy to (re)create python testing environment.
2023-06-19 16:24:03 +00:00
link2xt
5659c1b9c2 refactor: do not treat messages without headers as a special case 2023-06-19 12:00:03 +00:00
link2xt
d538d29b94 docs: document how to regenerate Node.js constants before the release 2023-06-17 14:30:11 +00:00
link2xt
b4209fac2e ci(concourse): install venv before trying to use it
This is a follow-up to cbe1671104

I changed `apt-get` arguments for x86_64 glibc builds,
but forgot to change it for x86_64 musl, aarch64 glibc and aarch64 musl.

Because of this, `upload-wheels` task failed with a message:
```
The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.11-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.
```
2023-06-16 19:15:05 +00:00
link2xt
4d6dfa120e docs: add missing links for 1.116.0 and 1.117.0 to the changelog 2023-06-16 17:18:04 +00:00
link2xt
f92108be1d chore(release): prepare for 1.117.0 2023-06-16 16:42:17 +00:00
link2xt
00cb72f04d fix(dehtml): do not insert unnecessary newlines when parsing <p> tags
Previously, parsing of `<p>Foo</p><p>Bar</p>`
resulted in `\n\nFoo\n\n\n\nBar\n\n`.

Now it results in `Foo\n\nBar`.
2023-06-16 16:27:14 +00:00
link2xt
92e34d67e6 chore: add openrpc.json to .gitignore 2023-06-16 14:32:09 +00:00
link2xt
65bff8339f chore: update generated node files 2023-06-16 14:27:45 +00:00
Sebastian Klähn
768f8175e6 api(rust): Add api endpoint get_status_update (#4468)
* start

* derive default

* make some webxdc file public

* shorten code

* Add from<u32> for chatid

* reduce changes to a bare minimum

* fix nested errors

* @hocuris fixes

* fix @link2xt changes

---------

Co-authored-by: septias <xxsebastian.kleahnxx@gmail.com>
2023-06-15 15:35:57 +02:00
link2xt
c3f352aff1 fix(dehtml): skip links with empty text 2023-06-14 15:41:38 +00:00
link2xt
5ac2d1b8cb ci: remove mergeable configuration
Mergeable is disabled because it was requiring
that PR title follows conventional commit notation
even when PR consisted of multiple commits
and was not planned to be squash merged.
2023-06-14 14:59:33 +00:00
link2xt
8214b2b8c1 docs: document how conventional commits interact with squash merges 2023-06-14 14:59:33 +00:00
link2xt
53ab8a3b35 fix: update to async-imap 0.9.0 to remove deprecated ouroboros dependency
`ouroboros` is deprecated with a security advisory recommending
switch to `self_cell` crate:
https://rustsec.org/advisories/RUSTSEC-2023-0042

async-imap 0.9.0 depends on `self_cell` instead of `ouroboros`.
2023-06-14 15:46:42 +02:00
link2xt
cbe1671104 ci(concourse): install devpi in a virtual environment
This commit solves the "error: externally-managed-environment"
which started appearing since Debian 12 release.
`debian` is used as an Docker image to run devpi.
2023-06-13 16:51:53 +00:00
link2xt
0d0e223238 test(python): replace legacy tmpdir fixture with tmp_path 2023-06-12 15:14:25 +00:00
Simon Laux
4767f1ce74 docs: readme remove legacy from dc-node, mark napi as experimental 2023-06-10 00:29:59 +02:00
link2xt
1a62b6d77f refactor: rename MimeMessage.header into MimeMessage.headers 2023-06-09 22:20:46 +00:00
link2xt
915008d474 build: use 1 codegen-units for release builds 2023-06-08 16:25:14 +00:00
link2xt
9646766793 build: disable unused brotli feature "ffi-api" 2023-06-08 00:02:11 +00:00
link2xt
e948ec3256 test: regression test for case-sensitive comparison of gossip header to contact address 2023-06-07 19:50:42 +00:00
link2xt
9ab9d2eb7b fix: ignore address case when comparing the To: field to Autocrypt-Gossip: 2023-06-07 19:50:42 +00:00
link2xt
437f8c48c4 api(python): make Contact.is_verified() return bool 2023-06-07 19:50:42 +00:00
link2xt
e6d9a49187 api: emit DC_EVENT_MSGS_CHANGED per chat when messages are deleted 2023-06-07 09:07:21 +00:00
link2xt
33a014eea4 feat: add MsgDeleted event 2023-06-07 09:07:21 +00:00
link2xt
9be871ccf6 fix: emit DC_EVENT_MSGS_CHANGED without IDs when the message expires
Specifying msg IDs that cannot be loaded in the event payload
results in an error when the UI tries to load the message.
Instead, emit an event without IDs
to make the UI reload the whole messagelist.
2023-06-07 09:07:21 +00:00
Sebastian Klähn
6eb8abe535 feat: new group membership update algorithm
New algorithm improves group consistency
in cases of missing messages,
restored old backups and replies from classic MUAs.

Co-authored-by: Hocuri <hocuri@gmx.de>
Co-authored-by: link2xt <link2xt@testrun.org>
2023-06-06 23:49:55 +00:00
link2xt
91bf87fa80 fix: update from yanked libc 0.2.145 to 0.2.146
https://github.com/rust-lang/libc/issues/3264
2023-06-06 22:45:17 +00:00
link2xt
a2599ef08a ci: run cargo check with musl libc 2023-06-06 22:45:17 +00:00
link2xt
22d0a4bb32 build: use Rust 1.70.0 to compile deltachat-rpc-server releases 2023-06-06 22:45:17 +00:00
link2xt
7a160033b6 chore(release): prepare for 1.116.0 2023-06-05 19:11:07 +00:00
link2xt
3442748be7 ci: update clippy to 1.70.0 2023-06-05 18:52:30 +00:00
dependabot[bot]
d451bcfbe3 Merge pull request #4452 from deltachat/dependabot/cargo/percent-encoding-2.3.0 2023-06-05 18:51:57 +00:00
link2xt
b2993242e4 docs(python): document pytest fixtures
These docstrings are displayed by `pytest --fixtures`
when `deltachat` package is installed from PyPI.
2023-06-05 18:34:27 +00:00
dependabot[bot]
5eaa9eeed2 chore(cargo): bump percent-encoding from 2.2.0 to 2.3.0
Bumps [percent-encoding](https://github.com/servo/rust-url) from 2.2.0 to 2.3.0.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.2.0...v2.3.0)

---
updated-dependencies:
- dependency-name: percent-encoding
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-05 11:04:55 +00:00
dependabot[bot]
3ed2ac8f0c Merge pull request #4429 from deltachat/dependabot/cargo/uuid-1.3.3 2023-06-05 11:00:45 +00:00
dependabot[bot]
0145203f7b Merge pull request #4432 from deltachat/dependabot/cargo/proptest-1.2.0 2023-06-05 10:29:23 +00:00
dependabot[bot]
59588b319e cargo: bump uuid from 1.3.2 to 1.3.3
Bumps [uuid](https://github.com/uuid-rs/uuid) from 1.3.2 to 1.3.3.
- [Release notes](https://github.com/uuid-rs/uuid/releases)
- [Commits](https://github.com/uuid-rs/uuid/compare/1.3.2...1.3.3)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-05 10:14:10 +00:00
link2xt
f917c7de6b chore(cargo): bump criterion from 0.4.0 to 0.5.1 2023-06-05 10:12:27 +00:00
dependabot[bot]
84888fa4c4 cargo: bump proptest from 1.1.0 to 1.2.0
Bumps [proptest](https://github.com/proptest-rs/proptest) from 1.1.0 to 1.2.0.
- [Release notes](https://github.com/proptest-rs/proptest/releases)
- [Changelog](https://github.com/proptest-rs/proptest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/proptest-rs/proptest/compare/v1.1.0...v1.2.0)

---
updated-dependencies:
- dependency-name: proptest
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 22:42:06 +00:00
link2xt
e0b1644488 ci: run node.js lint on Windows 2023-06-04 22:39:15 +00:00
link2xt
4beba8ce3c chore(gitattributes): configure LF line endings for JavaScript files 2023-06-04 22:39:15 +00:00
dependabot[bot]
bc521a685d chore(cargo): bump once_cell from 1.17.1 to 1.18.0
Bumps [once_cell](https://github.com/matklad/once_cell) from 1.17.1 to 1.18.0.
- [Changelog](https://github.com/matklad/once_cell/blob/master/CHANGELOG.md)
- [Commits](https://github.com/matklad/once_cell/compare/v1.17.1...v1.18.0)

---
updated-dependencies:
- dependency-name: once_cell
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 18:54:12 -03:00
dependabot[bot]
33caa0f499 Merge pull request #4441 from deltachat/dependabot/cargo/tokio-1.28.2 2023-06-04 18:10:06 +00:00
dependabot[bot]
033ce41c0f Merge pull request #4450 from deltachat/dependabot/cargo/libc-0.2.145 2023-06-04 18:09:43 +00:00
dependabot[bot]
88a62e1f6e chore(cargo): bump libc from 0.2.142 to 0.2.145
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.142 to 0.2.145.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.142...0.2.145)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 14:24:50 +00:00
dependabot[bot]
dd30f6ab7d cargo: bump tokio from 1.28.0 to 1.28.2
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.28.0 to 1.28.2.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.28.0...tokio-1.28.2)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 14:24:16 +00:00
dependabot[bot]
140d116d98 Merge pull request #4438 from deltachat/dependabot/cargo/chrono-0.4.26 2023-06-04 14:23:24 +00:00
dependabot[bot]
d96b783909 cargo: bump chrono from 0.4.24 to 0.4.26
Bumps [chrono](https://github.com/chronotope/chrono) from 0.4.24 to 0.4.26.
- [Release notes](https://github.com/chronotope/chrono/releases)
- [Changelog](https://github.com/chronotope/chrono/blob/main/CHANGELOG.md)
- [Commits](https://github.com/chronotope/chrono/compare/v0.4.24...v0.4.26)

---
updated-dependencies:
- dependency-name: chrono
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 13:41:48 +00:00
dependabot[bot]
572c7f2efb Merge pull request #4434 from deltachat/dependabot/cargo/base64-0.21.2 2023-06-04 13:40:51 +00:00
link2xt
bcd6c226f6 ci: document why node prebuilds are built in a container 2023-06-04 13:30:24 +00:00
link2xt
bae61746f8 fix: build deltachat-node prebuilds on Debian 10
This reduces glibc version requirement
and makes sure it does not increase
as Ubuntu version on CI runners is updated.
2023-06-04 12:35:12 +00:00
dependabot[bot]
31f2766074 cargo: bump base64 from 0.21.0 to 0.21.2
Bumps [base64](https://github.com/marshallpierce/rust-base64) from 0.21.0 to 0.21.2.
- [Changelog](https://github.com/marshallpierce/rust-base64/blob/master/RELEASE-NOTES.md)
- [Commits](https://github.com/marshallpierce/rust-base64/compare/v0.21.0...v0.21.2)

---
updated-dependencies:
- dependency-name: base64
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-04 10:33:01 +00:00
link2xt
b06c8baa9c chore(cargo): bump pretty_env_logger from 0.4.0 to 0.5.0 2023-06-04 10:31:29 +00:00
dependabot[bot]
1e479fe4a3 Merge pull request #4431 from deltachat/dependabot/cargo/serde-1.0.163 2023-06-04 09:13:42 +00:00
link2xt
8ea8ee02ed ci: add top comments to GH Actions workflows 2023-06-02 20:19:57 +00:00
link2xt
55bc556bcf ci: use working-directory instead of cd command 2023-06-02 17:00:27 +00:00
link2xt
3b6d21301b ci: remove broken node-delete-preview.yml workflow
Old previews should be deleted by the cronjob
running on the `download.delta.chat` server.
2023-06-02 16:50:15 +00:00
dependabot[bot]
472195c7d9 cargo: bump serde from 1.0.160 to 1.0.163
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.160 to 1.0.163.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.160...v1.0.163)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-02 15:26:34 +00:00
dependabot[bot]
afb8b5ce55 Merge pull request #4435 from deltachat/dependabot/cargo/toml-0.7.4 2023-06-02 15:25:40 +00:00
dependabot[bot]
de3c82ef43 cargo: bump toml from 0.7.3 to 0.7.4
Bumps [toml](https://github.com/toml-rs/toml) from 0.7.3 to 0.7.4.
- [Commits](https://github.com/toml-rs/toml/compare/toml-v0.7.3...toml-v0.7.4)

---
updated-dependencies:
- dependency-name: toml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-02 13:49:25 +00:00
dependabot[bot]
4255ae4c2d cargo: bump log from 0.4.17 to 0.4.18
Bumps [log](https://github.com/rust-lang/log) from 0.4.17 to 0.4.18.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.17...0.4.18)

---
updated-dependencies:
- dependency-name: log
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-02 12:28:21 +00:00
dependabot[bot]
4b4e2f700e Merge pull request #4437 from deltachat/dependabot/cargo/syn-2.0.18 2023-06-02 12:27:32 +00:00
dependabot[bot]
81fde5c680 Merge pull request #4436 from deltachat/dependabot/cargo/reqwest-0.11.18 2023-06-02 12:26:56 +00:00
dependabot[bot]
5340a7d033 cargo: bump syn from 2.0.15 to 2.0.18
Bumps [syn](https://github.com/dtolnay/syn) from 2.0.15 to 2.0.18.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/2.0.15...2.0.18)

---
updated-dependencies:
- dependency-name: syn
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-02 10:31:52 +00:00
dependabot[bot]
fc82d728fc cargo: bump reqwest from 0.11.17 to 0.11.18
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.11.17 to 0.11.18.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.11.17...v0.11.18)

---
updated-dependencies:
- dependency-name: reqwest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-02 10:31:34 +00:00
link2xt
136e9179e9 ci(dependabot): use chore prefix for dependency updates 2023-06-02 10:30:34 +00:00
link2xt
31e19ca56c chore(cargo): bump regex from 1.8.1 to 1.8.3 2023-06-02 10:28:58 +00:00
link2xt
f2b02b7bb0 docs: document how to get Concourse CI secrets from pass 2023-06-01 19:50:42 +00:00
link2xt
646ace8e7a chore: add link to the changelog 2023-06-01 12:54:12 +00:00
link2xt
a2495716b6 Merge tag 'v1.112.10' 2023-06-01 12:53:10 +00:00
link2xt
0f579c6415 chore(release): prepare for 1.112.10 2023-06-01 12:49:20 +00:00
link2xt
3eddc9164c fix: disable fetch_existing_msgs setting by default
This caused too many problems after switching
the default setting for `show_emails`
from DC_SHOW_EMAILS_OFF to DC_SHOW_EMAILS_ALL
in <https://github.com/deltachat/deltachat-core-rust/pull/4019>

There is a topic <https://support.delta.chat/t/setting-no-chats-only-for-show-classic-e-mails-showing-classic-emails/2481>
on the forum with multiple requests to revert this setting
due to old emails being downloaded.
2023-06-01 11:11:36 +00:00
link2xt
dd29fae49b fix: update h2 to fix RUSTSEC-2023-0034 2023-05-31 19:00:20 +00:00
Franz Heinzmann (Frando)
5b435d11c7 feat(jsonrpc): generate OpenRPC definitions
When running `cargo test` in the deltachat-jsonrpc folder,
a new file `openrpc/openrpc.json` will be created with an
[OpenRPC](https://spec.open-rpc.org/) definition.

It can be copy-pasted into the
[OpenRPC playground](https://playground.open-rpc.org/)
and used to generate clients in other languages.
2023-05-21 22:11:07 +00:00
Hocuri
b9b0d20e8d test: Add golden tests infrastructure (#4395) 2023-05-21 22:10:33 +00:00
link2xt
c68a2e3820 ci: require Python 3.8 for deltachat-rpc-client
With Python 3.7 asynchronous tests randomly fail
with "RuntimeError: Event loop is closed" during shutdown.
Backtrace of the error includes `SafeChildWatcher` calls.

Python 3.8 has replaced `SafeChildWatcher`
with a new `ThreadedChildWatcher` by default [1]
as a bugfix for
"asyncio.create_subprocess_exec() only works with main event loop" bug [2].

Python 3.7 scheduled end of life is 2023-06-27
according to <https://devguide.python.org/versions/>.

[1] https://github.com/python/cpython/pull/14344
[2] https://bugs.python.org/issue35621
2023-05-21 13:08:03 +00:00
link2xt
c7ad0b1f4f test: make test_group_with_removed_message_id less flaky
It failed in CI once, apparently
because "Gr." was generated inside the group ID.
2023-05-21 11:50:41 +00:00
link2xt
0dd9e3a77e docs: add contributing guidelines
Co-authored-by: Hocuri <hocuri@gmx.de>
2023-05-20 10:34:02 +00:00
link2xt
d27e3d085e ci: remove incorrect comment 2023-05-19 11:03:26 +00:00
link2xt
10b2aa5350 chore: remove release.toml
We are not using cargo-release at the moment.
2023-05-19 09:25:27 +00:00
link2xt
3a29a555bf test(python): make test_mdn_asymmetric less flaky
Normally the message has UID 1,
but this is not true when account is reused.
In this case the message may be
"Marked messages 2 in folder DeltaChat as seen."
and the test times out waiting for
"Marked messages 1 in folder DeltaChat as seen."
2023-05-18 18:39:40 +00:00
link2xt
f024f396bf docs: document release process in RELEASE.md 2023-05-17 10:53:26 +00:00
link2xt
24d52c5909 build(set_core_version.py): expect release date in the changelog
git-cliff adds the date to the changelog automatically,
so set_core_version.py only needs to check that the date is in place.
2023-05-16 22:47:28 +00:00
link2xt
f9dc8edbcb feat: add more context to message loading errors 2023-05-16 19:40:38 +00:00
link2xt
2e6f98f4e4 api: add dc_jsonrpc_blocking_call() 2023-05-15 19:55:13 +00:00
link2xt
50431d8cfe build(git-cliff): add "Documentation" section 2023-05-15 15:34:16 +00:00
link2xt
55fcd589db build(git-cliff): put "ci" commits into "CI" section of changelog 2023-05-15 15:34:16 +00:00
link2xt
081178d623 ci(mergeable): allow PR titles to start with "ci" and "build" 2023-05-15 15:34:16 +00:00
link2xt
92d5857150 build(git-cliff): update the link to configuration documentation 2023-05-15 15:34:16 +00:00
link2xt
bb45c249a3 build(git-cliff): add unconventional commits to "Other" section 2023-05-15 15:34:16 +00:00
link2xt
8796e0472a build(git-cliff): add scope to changelog entries 2023-05-15 15:34:16 +00:00
link2xt
3bd16ba045 build(git-cliff): add "Build system" section 2023-05-15 15:34:16 +00:00
link2xt
4b7ff6f003 build(git-cliff): add period at the end of changelog entry titles
Make it consistent with the rest of the changelog.
2023-05-15 15:34:16 +00:00
link2xt
53449ea5b3 build(git-cliff): remove git-cliff footer 2023-05-15 15:34:16 +00:00
link2xt
3b381c4862 docs: update instructions for python devenv 2023-05-15 15:33:26 +00:00
link2xt
ce729263a5 chore(release): prepare for v1.115.0 2023-05-13 18:45:51 +00:00
link2xt
67480999c0 feat: do not cut incoming text if "bot" config is set 2023-05-13 15:53:48 +00:00
Simon Laux
fb8b9f60ce api: jsonrpc: new MessageReadReceipt type and get_message_read_receipts(account_id, message_id) jsonrpc method 2023-05-12 16:32:52 +02:00
Simon Laux
9ed36d4e05 api: rust: add get_msg_read_receipts(context, msg_id) - get the contacts that send read receipts for a message 2023-05-12 16:32:52 +02:00
link2xt
e3c01d76c4 fix: do not return an error from send_msg_to_smtp if retry limit is exceeded
This prevents sending the other messages for which the limit was not exceeded.
2023-05-12 13:26:37 +00:00
link2xt
cb7f96449d Merge tag 'v1.112.9' into 'master' 2023-05-12 11:35:30 +00:00
link2xt
e4f4dacaf0 chore(release): prepare for 1.112.9 2023-05-12 11:17:54 +00:00
link2xt
9fc1fe74ad fix: delete smtp rows when message sending is cancelled 2023-05-12 11:17:23 +00:00
link2xt
991089d98e feat: improve SMTP logging 2023-05-12 10:07:55 +00:00
link2xt
c7a250da31 fix: fetch at most 100 existing messages even if EXISTS was not received
According to RFC 3501, EXISTS must always be sent in response to SELECT.
But if the server does not send it for some reason,
async-imap uses the default value, so we will essentially fetch `1:*`
and downloading all messages may take a long time.
2023-05-12 10:07:29 +00:00
link2xt
c5b6bad956 fix: recreate smtp table with AUTOINCREMENT
This ensures the rows cannot be confused accidentally
when referred by row_id.
2023-05-12 09:53:58 +00:00
link2xt
c4534ff621 feat: improve SMTP logging 2023-05-12 09:53:32 +00:00
Hocuri
b2c299fa82 fix: Don't put a double dot at the end of error messages (#4398) 2023-05-11 18:43:22 +02:00
link2xt
68aa15950a fix: fix PR URL template in git-cliff configuration (#4396) 2023-05-11 17:43:52 +02:00
Asiel Díaz Benítez
4a593a8d7e api!:jsonrpc: sort reactions in descending order (#4388)
convert `JSONRPCReactions.reactions` to a `Vec<JSONRPCReaction>` with unique reactions and their count, sorted in descending order.
---------

Co-authored-by: link2xt <link2xt@testrun.org>
2023-05-11 08:29:43 -04:00
Hocuri
2328ba54be feat: Generate our changelogs using git-cliff (#4393) 2023-05-10 18:18:42 +02:00
link2xt
e216dfd655 fix: delete smtp rows when message sending is cancelled 2023-05-10 16:08:00 +00:00
link2xt
86472aba2c refactor: iterate over msg_ids without .iter() 2023-05-10 14:32:38 +00:00
link2xt
15ce54edfb Update set_core_version.py with new release process 2023-05-10 12:00:14 +00:00
Sebastian Klähn
b7bbb3ee9a Allow sending a raw webxdc status update (#4386)
- create new api endpoint

Co-authored-by: bjoern <r10s@b44t.com>

* renaming function

---------

Co-authored-by: septias <xxsebastian.kleahnxx@gmail.com>
Co-authored-by: bjoern <r10s@b44t.com>
2023-05-09 21:15:09 +02:00
link2xt
d3236e79fd fix: fetch at most 100 existing messages even if EXISTS was not received
According to RFC 3501, EXISTS must always be sent in response to SELECT.
But if the server does not send it for some reason,
async-imap uses the default value, so we will essentially fetch `1:*`
and downloading all messages may take a long time.
2023-05-09 10:56:01 +00:00
Simon Laux
aa212b2b7e jsonrpc: MessageSearchResult, always include chat_name(not an option anymore), also add author_id and chat_type (#4374)
* jsonrpc: `MessageSearchResult`, always include `chat_name`(not an option anymore), also add `author_id` and `chat_type`

* replace .ok_or_else with anyhow context
2023-05-09 10:22:32 +00:00
Simon Laux
a0c51b3c3a fix: jsonrpc: typescript client: fix types of events in event emitter (#4373)
* fix: jsonrpc: typescript client: fix types of events in event emitter

* add ts ignore to remove ts error (when building in ts5)

doing the types right via casting is to complicated IMO and has no real benefit here.
2023-05-09 09:57:49 +00:00
link2xt
e50d7724e3 feat: build deltachat-rpc-server releases for x86_64 macOS 2023-05-08 19:04:38 +00:00
meganoahj
0d30e66dda add thumbnail for image in chatlist item (#4311)
* add thumbnail for image in chatlist item

* added preview for stickers and gifs also

* added last_message_type and last_message_id to ChatListItemFetchResult

addresses link2ext comment

* code optimization

fixes:
https://github.com/deltachat/deltachat-core-rust/pull/4311#discussion_r1162791672

* code formatting

* fix clippy

* add changelog entry

---------

Co-authored-by: meganoahj <s3ccg@testrun.org>
Co-authored-by: Simon Laux <mobile.info@simonlaux.de>
2023-05-08 19:44:43 +02:00
Asiel Díaz Benítez
5c3df7e452 jsonrpc: use camel-case for Event struct and move events.rs to types folder (#4372)
* use camel-case for Event struct and move events.rs to types folder

---------

Co-authored-by: link2xt <link2xt@testrun.org>
2023-05-08 06:49:19 -04:00
dependabot[bot]
3efbe5b1ef cargo: bump regex from 1.7.3 to 1.8.1 (#4361) 2023-05-07 13:31:29 +00:00
dependabot[bot]
52cfba06ea Merge pull request #4356 from deltachat/dependabot/cargo/dirs-5.0.1 2023-05-06 17:58:24 +00:00
dependabot[bot]
afba63603e cargo: bump dirs from 5.0.0 to 5.0.1
Bumps [dirs](https://github.com/soc/dirs-rs) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/soc/dirs-rs/releases)
- [Commits](https://github.com/soc/dirs-rs/commits)

---
updated-dependencies:
- dependency-name: dirs
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-06 11:36:44 +00:00
dependabot[bot]
3a25d6a44e Merge pull request #4362 from deltachat/dependabot/cargo/human-panic-1.1.4 2023-05-06 11:35:30 +00:00
dependabot[bot]
0688895022 Merge pull request #4360 from deltachat/dependabot/cargo/axum-0.6.18 2023-05-05 21:35:26 +00:00
dependabot[bot]
ce0e5416e6 cargo: bump human-panic from 1.1.3 to 1.1.4
Bumps [human-panic](https://github.com/rust-cli/human-panic) from 1.1.3 to 1.1.4.
- [Release notes](https://github.com/rust-cli/human-panic/releases)
- [Changelog](https://github.com/rust-cli/human-panic/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-cli/human-panic/compare/v1.1.3...v1.1.4)

---
updated-dependencies:
- dependency-name: human-panic
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-05 21:24:47 +00:00
link2xt
7918a6801e scripts/deny.sh: update package cache before running cargo deny 2023-05-05 21:23:10 +00:00
link2xt
6af631e8df Add JSON-RPC API to get reactions 2023-05-05 20:49:55 +00:00
dependabot[bot]
625ecaa9b5 cargo: bump axum from 0.6.12 to 0.6.18
Bumps [axum](https://github.com/tokio-rs/axum) from 0.6.12 to 0.6.18.
- [Release notes](https://github.com/tokio-rs/axum/releases)
- [Changelog](https://github.com/tokio-rs/axum/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/axum/compare/axum-v0.6.12...axum-v0.6.18)

---
updated-dependencies:
- dependency-name: axum
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-05 20:31:03 +00:00
dependabot[bot]
24fe1b9c15 Merge pull request #4364 from deltachat/dependabot/cargo/tokio-1.28.0 2023-05-05 20:29:57 +00:00
link2xt
ba36d09c70 Make the bots automatically accept group chat contact requests 2023-05-05 16:37:34 +00:00
link2xt
f57be7187e Update deny.toml 2023-05-05 13:23:44 +00:00
dependabot[bot]
6a00338f79 cargo: bump tokio from 1.27.0 to 1.28.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.27.0 to 1.28.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.27.0...tokio-1.28.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-05 10:48:24 +00:00
dependabot[bot]
16906210e1 Merge pull request #4354 from deltachat/dependabot/cargo/tokio-util-0.7.8 2023-05-05 10:47:12 +00:00
dependabot[bot]
f9b4540387 Merge pull request #4358 from deltachat/dependabot/cargo/syn-2.0.15 2023-05-05 10:46:48 +00:00
dependabot[bot]
9755438d0d Merge pull request #4366 from deltachat/dependabot/cargo/serde-1.0.160 2023-05-05 10:44:58 +00:00
dependabot[bot]
fe9534ed7d cargo: bump serde from 1.0.159 to 1.0.160
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.159 to 1.0.160.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.159...v1.0.160)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 10:55:01 +00:00
dependabot[bot]
134c9ada68 cargo: bump syn from 2.0.13 to 2.0.15
Bumps [syn](https://github.com/dtolnay/syn) from 2.0.13 to 2.0.15.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/2.0.13...2.0.15)

---
updated-dependencies:
- dependency-name: syn
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 10:54:57 +00:00
dependabot[bot]
a3240452ff cargo: bump tokio-util from 0.7.7 to 0.7.8
Bumps [tokio-util](https://github.com/tokio-rs/tokio) from 0.7.7 to 0.7.8.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-util-0.7.7...tokio-util-0.7.8)

---
updated-dependencies:
- dependency-name: tokio-util
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 10:54:42 +00:00
dependabot[bot]
84beb6647d Merge pull request #4357 from deltachat/dependabot/cargo/serde_json-1.0.96 2023-05-03 10:53:51 +00:00
dependabot[bot]
ecf7e2d909 Merge pull request #4359 from deltachat/dependabot/cargo/libc-0.2.142 2023-05-03 10:10:06 +00:00
dependabot[bot]
fcfcf4bbf3 Merge pull request #4365 from deltachat/dependabot/cargo/quick-xml-0.28.2 2023-05-03 10:09:37 +00:00
dependabot[bot]
c62b6d77b7 Merge pull request #4368 from deltachat/dependabot/cargo/anyhow-1.0.71 2023-05-03 10:09:14 +00:00
dependabot[bot]
7e51b9686f cargo: bump quick-xml from 0.28.1 to 0.28.2
Bumps [quick-xml](https://github.com/tafia/quick-xml) from 0.28.1 to 0.28.2.
- [Release notes](https://github.com/tafia/quick-xml/releases)
- [Changelog](https://github.com/tafia/quick-xml/blob/master/Changelog.md)
- [Commits](https://github.com/tafia/quick-xml/compare/v0.28.1...v0.28.2)

---
updated-dependencies:
- dependency-name: quick-xml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 01:54:26 +00:00
dependabot[bot]
542ec4cac4 cargo: bump anyhow from 1.0.70 to 1.0.71
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.70 to 1.0.71.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.70...1.0.71)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 01:54:07 +00:00
dependabot[bot]
64b25d9ec0 cargo: bump serde_json from 1.0.95 to 1.0.96
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.95 to 1.0.96.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.95...v1.0.96)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-03 01:54:04 +00:00
dependabot[bot]
f91b6fbdf0 Merge pull request #4363 from deltachat/dependabot/cargo/reqwest-0.11.17 2023-05-03 01:53:12 +00:00
dependabot[bot]
41445a506e Merge pull request #4369 from deltachat/dependabot/cargo/futures-lite-1.13.0 2023-05-03 01:52:22 +00:00
dependabot[bot]
798db9d019 Merge pull request #4367 from deltachat/dependabot/cargo/tokio-stream-0.1.14 2023-05-02 23:48:34 +00:00
dependabot[bot]
2e860c32ab Merge pull request #4355 from deltachat/dependabot/cargo/uuid-1.3.2 2023-05-02 23:46:59 +00:00
dependabot[bot]
0e1faed6e5 cargo: bump futures-lite from 1.12.0 to 1.13.0
Bumps [futures-lite](https://github.com/smol-rs/futures-lite) from 1.12.0 to 1.13.0.
- [Release notes](https://github.com/smol-rs/futures-lite/releases)
- [Changelog](https://github.com/smol-rs/futures-lite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/smol-rs/futures-lite/compare/v1.12.0...v1.13.0)

---
updated-dependencies:
- dependency-name: futures-lite
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 22:03:16 +00:00
dependabot[bot]
f5de3be977 cargo: bump tokio-stream from 0.1.12 to 0.1.14
Bumps [tokio-stream](https://github.com/tokio-rs/tokio) from 0.1.12 to 0.1.14.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Changelog](https://github.com/tokio-rs/tokio/blob/tokio-0.1.14/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-stream-0.1.12...tokio-0.1.14)

---
updated-dependencies:
- dependency-name: tokio-stream
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 22:02:36 +00:00
dependabot[bot]
4b0a30eb66 cargo: bump reqwest from 0.11.16 to 0.11.17
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.11.16 to 0.11.17.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.11.16...v0.11.17)

---
updated-dependencies:
- dependency-name: reqwest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 22:00:52 +00:00
dependabot[bot]
7710467571 cargo: bump libc from 0.2.140 to 0.2.142
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.140 to 0.2.142.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.140...0.2.142)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 21:59:05 +00:00
dependabot[bot]
1687794b81 cargo: bump uuid from 1.3.0 to 1.3.2
Bumps [uuid](https://github.com/uuid-rs/uuid) from 1.3.0 to 1.3.2.
- [Release notes](https://github.com/uuid-rs/uuid/releases)
- [Commits](https://github.com/uuid-rs/uuid/compare/1.3.0...1.3.2)

---
updated-dependencies:
- dependency-name: uuid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-01 21:57:42 +00:00
link2xt
158541f05c Document deltachat_rpc_client installation 2023-04-29 13:53:57 +00:00
link2xt
eb28899cd0 Add 1.112.8 link to the changelog 2023-04-27 10:28:38 +00:00
link2xt
432046225a Fix 1.114.0 link in the changelog 2023-04-27 10:27:39 +00:00
Simon Laux
bf958ce6c1 More context for chat and chatlist errors (#3932) 2023-04-25 17:20:26 -04:00
Simon Laux
ea8ee4e67d jsonrpc: Remove message id from chatlist item (#3071)
Why? because desktop currently fetches the chatlist multiple times, even though it just needs the
chatlistitem for one chat.

Note: @r10s was worried before that exposing the method to get a single updated chatlistitem could
lead to race conditions where the chatlist item is newer than the chatlist order. But I don't think
this will change anything for desktop besides making it a little faster (because currently desktop
fetches the whole chatlist instead of just the entry it needs when an entry updates).
2023-04-25 17:20:26 -04:00
link2xt
edfdbbdc90 Release 1.114.0 2023-04-24 22:31:17 +00:00
Simon Laux
1b8bfef441 jsonrpc: make event loop in ts client optional (#4347)
* jsonrpc: make event loop in ts client optional

* jsonrpc: ts: fix tests and make specifying `startEventLoop` mandatory

* add changelog entry

* Update CHANGELOG.md
2023-04-24 23:18:55 +02:00
link2xt
514074de8b JSON-RPC: retrieve events via long polling
This way is more compatible to JSON-RPC libraries
that do not support receiving notifications from the server
and allows describing event types in the OpenRPC specification.

Event thread converting events to notifications in the FFI
is removed, so it is now possible to construct a dc_jsonrpc_instance_t
while still retrieving events via dc_event_emitter_t.
2023-04-22 16:42:59 +00:00
link2xt
e7aab5c67c Remove newline from release-date.in 2023-04-20 15:40:09 +00:00
link2xt
40484e875e deltachat-ffi: update read_url_blob for new .log_err() 2023-04-20 15:23:20 +00:00
link2xt
fc215ceb63 Merge v1.112.8 2023-04-20 15:09:55 +00:00
link2xt
2701c135db Prepare 1.112.8 2023-04-20 15:05:07 +00:00
link2xt
3a8df3e673 Do not use println! in JSON-RPC
This may break the output of deltachat-rpc-server
2023-04-20 14:15:18 +00:00
link2xt
fa95b269a5 Backport new set_core_version.py 2023-04-20 14:03:47 +00:00
B. Petersen
0e9f8c4726 describe dc_http_response_t, needed for doxygen's @memberof 2023-04-20 14:01:14 +00:00
link2xt
a8d4cbd5c1 Add C API to get HTTP responses 2023-04-20 14:01:14 +00:00
link2xt
f68a2fc387 JSON-RPC: return mimetype and encoding for HTTP blobs 2023-04-20 14:00:16 +00:00
link2xt
ede4e8109e Release 1.113.0 2023-04-18 18:54:41 +00:00
link2xt
663df6bdfd Replace 404 link with a web archive version 2023-04-18 18:53:39 +00:00
link2xt
d97bdd9fd0 Add more links to configure documentation 2023-04-18 18:53:39 +00:00
Hocuri
a806a218bf Clippy; remove forgotten dbg! (#4338) 2023-04-18 18:52:01 +00:00
link2xt
903633f422 Add regression test 2023-04-18 16:39:19 +00:00
link2xt
3c774b02e5 Only reset status to "" if a text/plain part without signature is received
Otherwise sending a message without plaintext part
resets the signature. It is particularly dangerous
in multidevice case, because it's easy to accidentally
reset the signature on your other device with a non-text message.
2023-04-18 16:39:19 +00:00
iequidoo
4aae48b0a1 Gracefully terminate deltachat-rpc-server on ctrl-c and SIGTERM (#4323) 2023-04-18 12:10:39 -04:00
iequidoo
a8b790a5db deltachat-rpc-server: Drop Accounts object when terminating (#4323)
Otherwise it continues to keep the sender side of the event emitter which prevents events_task from
stopping.
2023-04-18 12:10:39 -04:00
Hocuri
6a6ceb6875 Add send_recv() to test_utils.rs
link2xt approved orally
2023-04-18 16:08:19 +02:00
link2xt
37503dd3e8 JSON-RPC: add get_http_blob API 2023-04-18 13:50:50 +00:00
link2xt
3f615c8de6 Update h2 from 0.3.17 to 0.3.18
Version 0.3.17 is yanked.
2023-04-18 11:05:59 +00:00
link2xt
2ef5f2eb52 scheduler: use oneshot channel for "started" notifications
The senders are not used more than once.
2023-04-17 17:41:33 +00:00
link2xt
f267f6f756 Move event payloads to a submodule 2023-04-17 17:41:00 +00:00
link2xt
538db53887 accounts: comment fixes 2023-04-17 16:20:21 +00:00
link2xt
21349abed8 Fix newlines with prettier 2023-04-17 16:07:05 +00:00
link2xt
d2fb2bb2ca Merge 1.112.7 into master 2023-04-17 15:24:15 +00:00
link2xt
0b832fb9de Prepare 1.112.7 2023-04-17 15:18:37 +00:00
link2xt
179b9ba2cb Update to released async-imap 0.8.0
It fixes important bug in `ensure_capacity()` that
sometimes resulted in erroneous detection of EOF in IMAP response.
2023-04-17 10:50:13 +00:00
link2xt
9150e9fb38 Update crossbeam-channel from 0.5.7 to 0.5.8
0.5.7 is yanked.
2023-04-17 10:48:35 +00:00
link2xt
4716fcef94 Use sync RwLock for debug_logging
This avoids the need for potentially expensive block_in_place(),
but is unlikely to actually block the thread as holding write lock is rare.
2023-04-16 19:58:19 +00:00
link2xt
2b7ee85e30 debug_logging: use Context.emit_event() 2023-04-16 19:58:19 +00:00
link2xt
2b8888350b Debug logging refactoring
Move DebugLogging into debug logging module.
Remove Context.send_log_event().
Use blocking_read() instead of try_read() to
get read lock on debug_logging() in synchronous code.
Do not try to log events while holding a lock
on DebugLogging.
2023-04-16 19:58:19 +00:00
iequidoo
4dfe34eedc fix review comments 2023-04-16 15:32:36 -04:00
iequidoo
430a71288f Reduce + recode images to JPEG if they are too huge (#3956)
I.e. > 500K for the balanced media quality and 130K for the worse one. This can remove animation and
transparency from PNG/WebP, but then a user always can send an image as a file.

Also don't reduce wide/high images if they aren't huge. Among other benefits, this way most of PNG
screenshots aren't touched.

Also remove Exif from all images, not from JPEGs only.
2023-04-16 15:32:36 -04:00
iequidoo
350509d5d1 Remove metadata from avatars and JPEG images before sending (#4027)
If there's an Exif, rewrite the file to remove it. This implies recoding now though.
2023-04-16 15:32:36 -04:00
link2xt
5403fd849c Comment fixes 2023-04-16 00:47:01 +00:00
link2xt
fa87d2e225 New APIs for message processing loops
This patch adds new C APIs
dc_get_next_msgs() and dc_wait_next_msgs(),
and their JSON-RPC counterparts
get_next_msgs() and wait_next_msgs().

New configuration "last_msg_id"
tracks the last message ID processed by the bot.
get_next_msgs() returns message IDs above
the "last_msg_id".
wait_next_msgs() waits for new message notification
and calls get_next_msgs().
wait_next_msgs() can be used to build
a separate message processing loop
independent of the event loop.

Async Python API get_fresh_messages_in_arrival_order()
is deprecated in favor of get_next_messages().

Introduced Python APIs:
- Account.wait_next_incoming_message()
- Message.is_from_self()
- Message.is_from_device()

Introduced Rust APIs:
- Context.set_config_u32()
- Context.get_config_u32()
2023-04-15 21:27:45 +00:00
link2xt
28a13e98a6 Add JSON-RPC API can_send() 2023-04-14 21:09:32 +00:00
link2xt
b369a30544 Pass scripts/run-python-test.sh arguments to pytest 2023-04-14 16:24:08 +00:00
link2xt
318ed4e6e1 Fix pip install argument in python README
Attempt to run `pip install python` will
fail trying to install package from PyPI.
2023-04-14 16:23:34 +00:00
Hocuri
c6a64e8d93 Don't let blocking be bypassed using groups (#4316)
* Don't let blocking be bypassed using groups

Fix #4313

* Fix another bug: A blocked group was sometimes not unblocked when an unblocked contact sent a message into it.
2023-04-13 22:45:47 +02:00
dependabot[bot]
efd6937dfa Merge pull request #4321 from deltachat/dependabot/cargo/fuzz/h2-0.3.17 2023-04-13 20:09:29 +00:00
dependabot[bot]
36bf1fe3f6 Merge pull request #4322 from deltachat/dependabot/cargo/h2-0.3.17 2023-04-13 20:09:17 +00:00
dependabot[bot]
4da0e9ac64 cargo: bump h2 from 0.3.16 to 0.3.17
Bumps [h2](https://github.com/hyperium/h2) from 0.3.16 to 0.3.17.
- [Release notes](https://github.com/hyperium/h2/releases)
- [Changelog](https://github.com/hyperium/h2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/hyperium/h2/compare/v0.3.16...v0.3.17)

---
updated-dependencies:
- dependency-name: h2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-13 17:07:57 +00:00
dependabot[bot]
436766f002 build(deps): bump h2 from 0.3.15 to 0.3.17 in /fuzz
Bumps [h2](https://github.com/hyperium/h2) from 0.3.15 to 0.3.17.
- [Release notes](https://github.com/hyperium/h2/releases)
- [Changelog](https://github.com/hyperium/h2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/hyperium/h2/compare/v0.3.15...v0.3.17)

---
updated-dependencies:
- dependency-name: h2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-13 17:04:54 +00:00
Hocuri
d4f2507288 Remove confusing log "ignoring unsolicited response Recent(…)" (#3934)
It doesn't seem to add value and gives the impression that something
went wrong.
2023-04-13 16:27:25 +00:00
Hocuri
28fd27476f Small verification fixes (#4317)
* Small performance improvement by not unnecessarily loading the peerstate

* Remove wrong info message "{contact} verified" when scanning a QR code with just an email

I think that this was a bug in the original C code and then slipped
through two refactorings.
2023-04-13 16:14:23 +00:00
link2xt
619b849ce7 sql: cleanup usage of ToSql
Moved custom ToSql trait including Send + Sync from lib.rs to sql.rs.
Replaced most params! and paramsv! macro usage with tuples.

Replaced paramsv! and params_iterv! with params_slice!,
because there is no need to construct a vector.
2023-04-13 12:48:00 +00:00
iequidoo
f1eeb1df8c Cleanly terminate deltachat-rpc-server (#4234)
Do it as per "Thread safety" section in deltachat-ffi/deltachat.h. Also terminate on ctrl-c.
2023-04-12 17:20:42 -04:00
link2xt
cecc080931 Update crossbeam-channel to 0.5.8
0.5.7 is yanked
2023-04-11 18:45:37 +00:00
link2xt
11e6a325a2 ci: remove references to nonexistent matrix.rust 2023-04-08 18:27:35 +00:00
Sebastian Klähn
eed8e08145 Protect against RTLO attacks (#3609)
Protect against RTLO attackts
2023-04-07 08:36:37 +00:00
iequidoo
36bec9c295 Update "accounts.toml" atomically (#4295) 2023-04-06 22:52:25 -04:00
iequidoo
c8988f5a55 maybe_add_time_based_warnings(): Use release date instead of the provider DB update one (#4213)
bjoern <r10s@b44t.com> wrote:
> maybe_add_time_based_warnings() requires some date guaranteed to be in the near past. based on
this known date we check if the system clock is wrong (if earlier than known date) and if the used
Delta Chat version may be outdated (1 year passed since known date). while this does not catch all
situations, it catches quite some errors with comparable few effort.
>
> figuring out the date guaranteed to be in the near past is a bit tricky. that time, we added
get_provider_update_timestamp() for exactly that purpose - it is checked manually by some dev and
updated from time to time, usually before a release.
>
> however, meanwhile, the provider-db gets updated less frequently - things might be settled a bit
more - and, get_provider_update_timestamp() was also changed to return the date of the last commit,
instead of last run. while that seem to be more on-purpose, we cannot even do an “empty” database
update to update the known date.
>
> as get_provider_update_timestamp() is not used for anything else, maybe we should completely
remove that function and replace it by get_last_release_timestamp that is then updated by
./scripts/set_core_version.py - the result of that is reviewed manually anyway, so that seems to be
a good place (i prefer manual review here and mistrust further automation as also dev or ci clocks
may be wrong :)
2023-04-06 22:00:02 -04:00
Floris Bruynooghe
86c18fb3ae ref: More logging for ongoing and get_backup (#4289)
This adds a few log items for imex::transfer::get_backup and the
ongoing process to give some more insights.

IO is now also paused after the ongoing process is allocated in
get_backup to avoid needlessly pausing IO.
2023-04-04 18:11:45 +02:00
link2xt
2ba4381c39 Merge branch 'stable-1.112' into 'master' 2023-04-04 15:01:37 +00:00
link2xt
185a0193cc Fix newline at the end of package.json 2023-04-04 16:47:25 +02:00
B. Petersen
1b00334281 bump version to 1.112.6 2023-04-04 16:47:25 +02:00
B. Petersen
0eb2f5bf52 fix some CHANGELOG typos 2023-04-04 16:47:25 +02:00
B. Petersen
78d1aa46a1 update changelog for 1.112.6 2023-04-04 16:47:25 +02:00
link2xt
26403a1599 Update spin from 0.9.7 to 0.9.8
`spin` 0.9.7 is yanked: https://rustsec.org/advisories/RUSTSEC-2023-0031
2023-04-04 12:54:23 +00:00
B. Petersen
a1f112470e add a device message when backup transfer ends
that way, UI can just close the transfer dialog,
so that, at the end, both devices end in the chatlist.

we can also use this for troubleshooting -
if the device message is not present,
transfer did not succeed completely.

(a separate device message may be nice in that case -
but that is another effort,
same for making the device message reappear after deletion
or after some time)
2023-04-04 14:17:26 +02:00
dependabot[bot]
2ab7a37d85 Merge pull request #4297 from deltachat/dependabot/cargo/iroh-0.4.1 2023-04-04 09:02:11 +00:00
link2xt
4b933ed2ef Update to iroh 0.4.1 2023-04-04 09:00:19 +00:00
dependabot[bot]
0d1c12115d Merge pull request #4298 from deltachat/dependabot/cargo/fast-socks5-0.8.2 2023-04-04 08:34:30 +00:00
link2xt
3bced80b23 imap: use try_next() to avoid the need to transpose Option and Result 2023-04-04 08:23:37 +00:00
link2xt
f46f3e939e clippy fix 2023-04-04 09:50:42 +02:00
B. Petersen
9d8e836fdd show some text instead of nothing on empty quota list
some providers say that they support QUOTA in the IMAP CAPABILITY,
but return an empty list without any quota information then.

in our "Connectivity", this looks a bit of an error.

i have not seen this error often - only for testrun.org -
if it is usual, we could also just say "not supported"
(as we do in case QUOTA is not returned).
a translations seems not to be needed for now,
it seems unusual, and all other errors are not translated as well.
2023-04-04 09:50:42 +02:00
dependabot[bot]
132d34db5c cargo: bump fast-socks5 from 0.8.1 to 0.8.2
Bumps [fast-socks5](https://github.com/dizda/fast-socks5) from 0.8.1 to 0.8.2.
- [Release notes](https://github.com/dizda/fast-socks5/releases)
- [Commits](https://github.com/dizda/fast-socks5/compare/v0.8.1...v0.8.2)

---
updated-dependencies:
- dependency-name: fast-socks5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-03 22:22:51 +00:00
dependabot[bot]
16edb7b35a cargo: bump iroh from 0.4.0 to 0.4.1
Bumps [iroh](https://github.com/n0-computer/iroh) from 0.4.0 to 0.4.1.
- [Release notes](https://github.com/n0-computer/iroh/releases)
- [Changelog](https://github.com/n0-computer/iroh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/n0-computer/iroh/compare/v0.4.0...v0.4.1)

---
updated-dependencies:
- dependency-name: iroh
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-03 22:21:52 +00:00
link2xt
044478a044 Update fd-lock, is-terminal and tempfile 2023-04-03 21:56:16 +00:00
dependabot[bot]
f6ea48d666 Merge pull request #4275 from deltachat/dependabot/cargo/axum-0.6.12 2023-04-03 21:43:43 +00:00
dependabot[bot]
6ed3ed1617 cargo: bump axum from 0.6.11 to 0.6.12
Bumps [axum](https://github.com/tokio-rs/axum) from 0.6.11 to 0.6.12.
- [Release notes](https://github.com/tokio-rs/axum/releases)
- [Changelog](https://github.com/tokio-rs/axum/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/axum/compare/axum-v0.6.11...axum-v0.6.12)

---
updated-dependencies:
- dependency-name: axum
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-03 19:48:44 +00:00
link2xt
9c9c401e66 ci: use --all-targets --all-features for cargo check 2023-04-03 19:27:11 +00:00
link2xt
72031edfbe ci: split CI into more parallel jobs
With this, all the builds happen in parallel in 3-6 minutes,
and then python tests run for 8-9 minutes.

Before, it was 6-17 minutes for compilation,
then 19-31 minutes for python tests.
Compilation of the library and test binary was not parallelized,
and then python tests included async python tests
and deltachat-rpc-server binary compilation.

Now, deltachat-rpc-server compilation,
Rust testing and async python tests are separate jobs.
2023-04-03 19:27:11 +00:00
iequidoo
41456aa2ab jsonrpc API: Fix documentation of search_messages() (#4288) 2023-04-03 14:17:39 -04:00
link2xt
a70f29381a location: remove bitflags dependency 2023-04-03 16:56:37 +00:00
dependabot[bot]
3b0ad73732 Merge pull request #4270 from deltachat/dependabot/cargo/async_zip-0.0.12 2023-04-03 16:08:41 +00:00
dependabot[bot]
8c302648bb Merge pull request #4263 from deltachat/dependabot/cargo/tokio-1.27.0 2023-04-03 16:06:43 +00:00
dependabot[bot]
01b888c341 cargo: bump tokio from 1.26.0 to 1.27.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.26.0 to 1.27.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.26.0...tokio-1.27.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-03 12:33:21 +00:00
dependabot[bot]
f8e87a8b6c cargo: bump async_zip from 0.0.11 to 0.0.12
Bumps [async_zip](https://github.com/Majored/rs-async-zip) from 0.0.11 to 0.0.12.
- [Release notes](https://github.com/Majored/rs-async-zip/releases)
- [Commits](https://github.com/Majored/rs-async-zip/commits)

---
updated-dependencies:
- dependency-name: async_zip
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-03 12:33:19 +00:00
link2xt
01af83946c Update to released version of async-imap 2023-04-03 12:31:16 +00:00
link2xt
386a9ad0b0 Update from yanked spin 0.9.7 to 0.9.8 2023-04-03 10:21:11 +00:00
Floris Bruynooghe
c6c20d8f3c ref(scheduler): Make InnerSchedulerState an enum (#4251)
This is more verbose, but makes reasoning about things easier.
2023-04-03 11:13:44 +02:00
dependabot[bot]
40b072711e Merge pull request #4283 from deltachat/dependabot/cargo/rusqlite-0.29.0 2023-04-03 08:25:57 +00:00
Floris Bruynooghe
2469964a44 ref(sql): Do not warn if BLOBS_BACKUP_NAME does not exist (#4256)
ref(sql): Dop not warn if BLOBS_BACKUP_NAME does not exist

It is perfectly normal for this directory to not exist.
2023-04-03 09:28:17 +02:00
link2xt
40e0924768 Add bitflags exception to deny.toml 2023-04-03 07:25:44 +00:00
dependabot[bot]
e016440fb3 Merge pull request #4267 from deltachat/dependabot/cargo/serde_json-1.0.95 2023-04-02 22:06:59 +00:00
dependabot[bot]
a37aaa5585 Merge pull request #4271 from deltachat/dependabot/cargo/image-0.24.6 2023-04-02 22:06:26 +00:00
dependabot[bot]
1ee551d53e cargo: bump serde_json from 1.0.93 to 1.0.95
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.93 to 1.0.95.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.93...v1.0.95)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 19:55:56 +00:00
dependabot[bot]
2341eed796 Merge pull request #4282 from deltachat/dependabot/cargo/futures-0.3.28 2023-04-02 19:54:10 +00:00
dependabot[bot]
49cfd79505 Merge pull request #4265 from deltachat/dependabot/cargo/serde-1.0.159 2023-04-02 19:41:36 +00:00
dependabot[bot]
9ac0d1a1ce Merge pull request #4280 from deltachat/dependabot/cargo/thiserror-1.0.40 2023-04-02 19:00:26 +00:00
dependabot[bot]
6046dfabe9 cargo: bump rusqlite from 0.28.0 to 0.29.0
Bumps [rusqlite](https://github.com/rusqlite/rusqlite) from 0.28.0 to 0.29.0.
- [Release notes](https://github.com/rusqlite/rusqlite/releases)
- [Changelog](https://github.com/rusqlite/rusqlite/blob/master/Changelog.md)
- [Commits](https://github.com/rusqlite/rusqlite/compare/v0.28.0...v0.29.0)

---
updated-dependencies:
- dependency-name: rusqlite
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 18:32:07 +00:00
dependabot[bot]
c2269bf777 cargo: bump futures from 0.3.26 to 0.3.28
Bumps [futures](https://github.com/rust-lang/futures-rs) from 0.3.26 to 0.3.28.
- [Release notes](https://github.com/rust-lang/futures-rs/releases)
- [Changelog](https://github.com/rust-lang/futures-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/futures-rs/compare/0.3.26...0.3.28)

---
updated-dependencies:
- dependency-name: futures
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 17:40:49 +00:00
dependabot[bot]
b81a958021 Merge pull request #4278 from deltachat/dependabot/cargo/walkdir-2.3.3 2023-04-02 17:16:24 +00:00
dependabot[bot]
9e37a5643c cargo: bump thiserror from 1.0.38 to 1.0.40
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.38 to 1.0.40.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.38...1.0.40)

---
updated-dependencies:
- dependency-name: thiserror
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 16:42:22 +00:00
dependabot[bot]
50a213c2e1 cargo: bump serde from 1.0.152 to 1.0.159
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.152 to 1.0.159.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.152...v1.0.159)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 16:42:10 +00:00
link2xt
c6e9fbd501 Update syn crate in deltachat_derive 2023-04-02 16:40:23 +00:00
dependabot[bot]
720b5aa7c1 Merge pull request #4284 from deltachat/dependabot/cargo/toml-0.7.3 2023-04-02 16:30:33 +00:00
dependabot[bot]
7be7640d3f Merge pull request #4266 from deltachat/dependabot/cargo/reqwest-0.11.16 2023-04-02 16:07:43 +00:00
dependabot[bot]
e4d97278ee cargo: bump reqwest from 0.11.14 to 0.11.16
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.11.14 to 0.11.16.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.11.14...v0.11.16)

---
updated-dependencies:
- dependency-name: reqwest
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 15:07:16 +00:00
dependabot[bot]
793ad82d42 Merge pull request #4277 from deltachat/dependabot/cargo/libc-0.2.140 2023-04-02 15:04:51 +00:00
dependabot[bot]
2b4d846f0e Merge pull request #4285 from deltachat/dependabot/cargo/regex-1.7.3 2023-04-02 15:03:47 +00:00
dependabot[bot]
379eadab4f Merge pull request #4281 from deltachat/dependabot/cargo/anyhow-1.0.70 2023-04-02 14:45:24 +00:00
dependabot[bot]
53a41fcffe cargo: bump anyhow from 1.0.69 to 1.0.70
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.69 to 1.0.70.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.69...1.0.70)

---
updated-dependencies:
- dependency-name: anyhow
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 09:52:31 +00:00
link2xt
5e597e1f09 Merge tag 'v1.112.5' 2023-04-02 09:50:16 +00:00
link2xt
c9879f863b Prepare 1.112.5 release 2023-04-02 09:48:39 +00:00
dependabot[bot]
e1b260d0ec cargo: bump regex from 1.7.1 to 1.7.3
Bumps [regex](https://github.com/rust-lang/regex) from 1.7.1 to 1.7.3.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.7.1...1.7.3)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 09:19:42 +00:00
dependabot[bot]
480b05063d cargo: bump libc from 0.2.139 to 0.2.140
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.139 to 0.2.140.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.139...0.2.140)

---
updated-dependencies:
- dependency-name: libc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-02 09:17:54 +00:00
dependabot[bot]
8477f7b472 Merge pull request #4276 from deltachat/dependabot/cargo/quick-xml-0.28.1 2023-04-02 09:17:40 +00:00
dependabot[bot]
91ae4eab06 Merge pull request #4268 from deltachat/dependabot/cargo/dirs-5.0.0 2023-04-02 09:14:21 +00:00
link2xt
f6d27516cb Run migrations before delete_and_reset_all_device_msgs()
Both when importing a backup from file or receiving it over the network.
2023-04-02 08:39:13 +00:00
dependabot[bot]
7b86681cb2 Merge pull request #4274 from deltachat/dependabot/cargo/testdir-0.7.3 2023-04-02 08:38:19 +00:00
dependabot[bot]
1de815441a Merge pull request #4272 from deltachat/dependabot/cargo/chrono-0.4.24 2023-04-02 08:37:11 +00:00
link2xt
d6426dc1b6 imex: run migrations after receiving a transferred backup
Similarly to how `imex_inner()` runs migrations
after successful call to `import_backup()`,
migrations should be run after receiving a backup
using `transfer_from_provider()`.
2023-04-01 23:56:36 +00:00
dependabot[bot]
44a36025b5 cargo: bump toml from 0.7.2 to 0.7.3
Bumps [toml](https://github.com/toml-rs/toml) from 0.7.2 to 0.7.3.
- [Release notes](https://github.com/toml-rs/toml/releases)
- [Commits](https://github.com/toml-rs/toml/compare/toml-v0.7.2...toml-v0.7.3)

---
updated-dependencies:
- dependency-name: toml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:04:59 +00:00
dependabot[bot]
00017ab653 cargo: bump walkdir from 2.3.2 to 2.3.3
Bumps [walkdir](https://github.com/BurntSushi/walkdir) from 2.3.2 to 2.3.3.
- [Release notes](https://github.com/BurntSushi/walkdir/releases)
- [Commits](https://github.com/BurntSushi/walkdir/compare/2.3.2...2.3.3)

---
updated-dependencies:
- dependency-name: walkdir
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:03:47 +00:00
dependabot[bot]
411adc861e cargo: bump quick-xml from 0.27.1 to 0.28.1
Bumps [quick-xml](https://github.com/tafia/quick-xml) from 0.27.1 to 0.28.1.
- [Release notes](https://github.com/tafia/quick-xml/releases)
- [Changelog](https://github.com/tafia/quick-xml/blob/master/Changelog.md)
- [Commits](https://github.com/tafia/quick-xml/compare/v0.27.1...v0.28.1)

---
updated-dependencies:
- dependency-name: quick-xml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:03:25 +00:00
dependabot[bot]
c5b3939ddb cargo: bump testdir from 0.7.2 to 0.7.3
Bumps testdir from 0.7.2 to 0.7.3.

---
updated-dependencies:
- dependency-name: testdir
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:02:46 +00:00
dependabot[bot]
a9e3ea56ec cargo: bump chrono from 0.4.23 to 0.4.24
Bumps [chrono](https://github.com/chronotope/chrono) from 0.4.23 to 0.4.24.
- [Release notes](https://github.com/chronotope/chrono/releases)
- [Changelog](https://github.com/chronotope/chrono/blob/main/CHANGELOG.md)
- [Commits](https://github.com/chronotope/chrono/compare/v0.4.23...v0.4.24)

---
updated-dependencies:
- dependency-name: chrono
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:02:27 +00:00
dependabot[bot]
6a0f17a983 cargo: bump image from 0.24.5 to 0.24.6
Bumps [image](https://github.com/image-rs/image) from 0.24.5 to 0.24.6.
- [Release notes](https://github.com/image-rs/image/releases)
- [Changelog](https://github.com/image-rs/image/blob/master/CHANGES.md)
- [Commits](https://github.com/image-rs/image/commits)

---
updated-dependencies:
- dependency-name: image
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:02:14 +00:00
dependabot[bot]
28e6f457b1 cargo: bump dirs from 4.0.0 to 5.0.0
Bumps [dirs](https://github.com/soc/dirs-rs) from 4.0.0 to 5.0.0.
- [Release notes](https://github.com/soc/dirs-rs/releases)
- [Commits](https://github.com/soc/dirs-rs/commits)

---
updated-dependencies:
- dependency-name: dirs
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-01 22:01:31 +00:00
link2xt
fdf46054e2 ci: limit artifact retention time for libdeltachat.a to 1 day
These artifacts are only needed to be downloaded
by the python test job immediately after building.
2023-04-01 17:37:52 +00:00
link2xt
47a3ee1ff1 ci: run mypy and doc with installed library
These require that package can be installed.
2023-04-01 13:29:55 +00:00
link2xt
a0b7b4b5c4 ci: use ' instead of " for condition quote 2023-04-01 12:58:29 +00:00
link2xt
b9bc0a4047 ci: fixup "if" expression 2023-04-01 12:56:36 +00:00
link2xt
e57abf92f3 ci: split library build and python tests into separate jobs
This way if flaky python tests fail,
it is possible to rerun them without having to rerun library compilation.
Python test jobs will redownload already built library artifact
and compile the bindings against it.
2023-04-01 12:53:49 +00:00
iequidoo
b56a7bc139 Fix CHANGELOG.md after c401780c 2023-04-01 09:13:08 -03:00
iequidoo
c401780c15 Compress mime_headers column with HTML emails stored in database (#4077)
Co-authored-by: bjoern <r10s@b44t.com>
2023-03-31 19:45:34 -03:00
iequidoo
df96a1daac test_moved_markseen: Expect DC_EVENT_MSGS_CHANGED also 2023-03-31 17:15:02 -03:00
iequidoo
0a2200c2c8 python: Wait for initial Resync in the bot tests 2023-03-31 17:15:02 -03:00
Floris Bruynooghe
61b8d04418 ref(logging): remove LogExt::log_or_ok (#4250)
This further reduces the cognitive overload of having many ways to do
something.  The same is very easily done using composition.  Followup
from 82ace72527.
2023-03-31 12:15:17 +02:00
link2xt
fd7cc83537 Merge tag 'v1.112.4'
Release 1.112.4
2023-03-31 01:13:56 +00:00
link2xt
f24843fbb1 Release 1.112.4 2023-03-31 01:12:26 +00:00
link2xt
6c57bc9438 Fix call to auditwheel in scripts/run_all.sh
This bugs prevents CI from building wheels.
2023-03-31 01:02:41 +00:00
link2xt
ae5f72cf4f Remove install_python_bindings.py script and update docs
`install_python_bindings.py` was not used by CI
and scripts, except for `scripts/run-python-test.sh`
which only used it to invoke `cargo`.

Instead of using an additional script,
run cargo directly.

The documentation is updated to remove
references to `install_python_bindings.py`.
The section "Installing bindings from source"
was in fact incorrect as it suggested
running `tox --devenv` first and only then
compiling the library with `install_python_bindings.py`.
Now it explicitly says to run cargo first
and then install the package without using `tox`.
`tox` is still used for running the tests
and setting up development environment.
2023-03-31 00:27:35 +00:00
link2xt
3e65b6f3a6 Update to rPGP 0.10.1 2023-03-30 21:09:29 +00:00
link2xt
a4a53d5299 Increase MSRV to 1.65.0 2023-03-30 21:09:29 +00:00
link2xt
4223cac7a5 set_core_version.py: add newline to the end of package.json 2023-03-30 20:38:47 +00:00
link2xt
0073a09da6 Merge v1.112.3 2023-03-30 20:37:43 +00:00
link2xt
e612927c5d Fix links in the changelog 2023-03-30 20:36:30 +00:00
link2xt
aff951440c Release 1.112.3 2023-03-30 20:32:49 +00:00
Floris Bruynooghe
ef63e01632 fix(imex): transfer::get_backup must always free ongoing process (#4249)
* fix(imex): transfer::get_backup must always free ongoing process

When the ongoing process is cancelled it is still the responsibility
of whoever took out the ongoing process to free it.  This code was
only freeing the ongoing process when completed normally but not when
cancelled.

* add changelog
2023-03-30 20:23:50 +00:00
link2xt
c4cf0f12c9 Prettier lint fix 2023-03-30 16:08:02 +00:00
link2xt
68635be8a2 Merge v1.112.2 into master 2023-03-30 15:42:27 +00:00
link2xt
776df7505e Remove upper limit on the attachment size
Recommended file size is used for recoding media.
For the upper size, we rely on the provider to tell us back
if the message cannot be delivered to some recipients.
This allows to send large files, such as APKs,
when using providers that don't have such strict limits.
2023-03-30 15:01:02 +00:00
link2xt
d6fdc7cb67 Release 1.112.2 2023-03-30 14:57:32 +00:00
Floris Bruynooghe
91c10b3ac6 feat(scheduler): Allow overlapping IoPauseGuards (#4246)
This enables using multiple pause guards at the same time.
2023-03-30 12:40:13 +02:00
Floris Bruynooghe
82ace72527 ref(logging): Remove message from LogExt::log_err (#4235)
This removes the message that needed to be supplied to LogExt::log_err
calls.  This was from a time before we adopted anyhow and now we are
better off using anyhow::Context::context for the message: it is more
consistent, composes better and is less custom.

The benefit of the composition can be seen in the FFI calls which need
to both log the error as well as return it to the caller via
the set_last_error mechanism.

It also removes the LogExt::ok_or_log_msg funcion for the same reason,
the message is obsoleted by anyhow's context.
2023-03-30 10:13:07 +02:00
link2xt
ea87c78d34 Do not return media from trashed messages in the "All media" view. 2023-03-30 08:10:06 +00:00
link2xt
585b8ece58 Remove outdated comment. 2023-03-30 08:07:21 +00:00
Floris Bruynooghe
a2927a6586 ref(deps): Upgrade to iroh 0.4.0 (#4245)
This moves us back to a released version;

- Ticket is now opaque, need to use accessor functions.

- Ticket now ensures it is valid itself, no need to inspect it's
  inners.  Deserialisation would fail if it was bad.

- The git version was accidentally used with default-features enabled
  and thus pulled in a few too many dependencies.  They are now gone.
2023-03-29 15:45:35 +02:00
Floris Bruynooghe
943c8a1ab3 feat(imex): Cancel BackupProvider when dropped (#4242)
This ensures that the BackupProvider will be stopped as soon as the
struct is dropped and the imex progress error event is emitted.  This
makes it easier to use and also makes sure that the ffi call
dc_backup_provider_unref() does not lead to dangling resources.
2023-03-29 14:51:08 +02:00
link2xt
3400f5641e Build zig-rpc-server for i686
cargo-zigbuild is replaced with a simple zig-cc wrapper.
cargo-zigbuild still tries to use i386-linux-musl triple,
while in zig 0.11 x86-linux-musl should be used [1].

This also gives us more control over compilation flags used
and prevents changes due to cargo-zigbuild upgrades,
as its version was not pinned.

[1] Merged PR "all: rename i386 to x86 "
    <https://github.com/ziglang/zig/pull/13101>
2023-03-29 10:56:22 +00:00
link2xt
5068648960 Update yanked spin 0.9.6
Otherwise cargo-deny complains.
2023-03-29 10:56:02 +00:00
Floris Bruynooghe
5be558ea68 feat(imex) Connect to all provider addresses concurrently (#4240)
This uses the new iroh API to connect to all provider addresses
concurrently.  It simplifies the implementation as well as we no
longer need to try the addresses manually.
2023-03-29 09:47:00 +02:00
link2xt
fc25bba514 Add changelog for unreleased 1.112.2 2023-03-28 10:44:07 +00:00
Floris Bruynooghe
20b326415a deps: Update iroh, remove default-net patch (#4239)
* deps: Update iroh, remove default-net patch

The released version of default-net is now sufficient and iroh makes
sure this dependency is recent enough.

* Update cargo-deny config

* Newer version of spin, previous has been yanked
2023-03-28 10:28:38 +00:00
link2xt
1bf5064039 Add unreleased section to changelog 2023-03-27 16:13:11 +00:00
link2xt
edf0c02bc8 Release 1.112.1 2023-03-27 15:22:31 +00:00
link2xt
1d42907114 deltachat-ffi: document thread safety guarantees 2023-03-27 14:47:40 +00:00
bjoern
070d832580 check against null in dc_backup_provider_unref() (#4232)
this is what we're doing in most comparable unref() functions.
2023-03-26 19:25:23 +02:00
link2xt
0dfec83b0f deltachat-rpc-client: configure setuptools_scm
This makes `python -m build` produce wheels with a version
other than 0.0.0.
2023-03-26 10:00:01 +00:00
link2xt
c84155cbd4 Add scripts/deny.sh
This can be used to manually run `cargo deny`
without specifying all the parameters manually.

Similar to existing scripts/clippy.sh
2023-03-25 19:54:24 +00:00
iequidoo
eb5ddf270f receive_imf: Mark special messages as seen (#3054)
Exactly: delivery reports, webxdc status updates.
2023-03-25 15:47:38 -03:00
link2xt
fb093253c6 Update generated nodejs constants files 2023-03-25 10:20:17 +00:00
dependabot[bot]
1864be5c55 Merge pull request #4229 from deltachat/dependabot/cargo/fuzz/openssl-0.10.48 2023-03-25 01:06:43 +00:00
dependabot[bot]
7138d44083 build(deps): bump openssl from 0.10.45 to 0.10.48 in /fuzz
Bumps [openssl](https://github.com/sfackler/rust-openssl) from 0.10.45 to 0.10.48.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.45...openssl-v0.10.48)

---
updated-dependencies:
- dependency-name: openssl
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-25 00:31:14 +00:00
Floris Bruynooghe
04daff0608 Add comment 2023-03-24 23:20:14 +00:00
Floris Bruynooghe
801250a9e0 feat(imex): Sort IP addresses for getting from ticket
When trying IP addresses from the ticket, have a very rough sort order
in which to try them.  Basically assume most local wifi's are
somewhere on 192.168.0.0/16 so prefer those first.
2023-03-24 23:20:14 +00:00
link2xt
20319b5426 Add --version option to deltachat-rpc-server 2023-03-24 23:11:11 +00:00
link2xt
9cca34bba5 Remove .wait_for_seen() calls in flaky tests
This is a merge commit for <https://github.com/deltachat/deltachat-core-rust/pull/4226>
2023-03-24 23:09:44 +00:00
link2xt
530981119e Update Cargo.lock 2023-03-24 23:08:46 +00:00
adbenitez
6d0327d057 deltachat-rpc-client: fix bug in Chat.send_message() 2023-03-24 18:56:08 -04:00
adbenitez
580ce5a9e9 deltachat-rpc-client: fix bug in Chat.send_message() 2023-03-24 17:34:41 -04:00
link2xt
6f327c950d Cargo.toml: replace branch with rev in default-net patch entry
This makes `cargo install --path deltachat-rpc-server` work again.
2023-03-24 21:16:04 +00:00
link2xt
92ad843ff2 Reduce test code duplication 2023-03-24 20:59:31 +00:00
link2xt
a8059c6bff python: remove flaky .wait_for_seen() from test_fetch_existing() 2023-03-24 18:09:40 +00:00
link2xt
4b468a25fe Remove pytest-rerunfailures
It is not compatible with pytest-timeout anyway:
<https://github.com/pytest-dev/pytest-rerunfailures/issues/99>
2023-03-24 16:13:33 +00:00
link2xt
1e135b649c Do not use IDLE in test_send_and_receive_message_markseen
Fix flakyness in case Dovecot sends only EXISTS
but not FETCH unsolicited response.
2023-03-24 16:09:40 +00:00
link2xt
40d32f2d0c Do not use IDLE in test_fetch_existing_msgs_group_and_single
Makes the test less flaky,
as Dovecot sometimes sends only the EXISTS response,
but not the FETCH response for flags.
2023-03-24 16:09:28 +00:00
link2xt
c9ec087cd8 python: do not use IDLE in test_markseen_message_and_mdn test
Make the test less flaky in case Dovecot notifies only about EXISTS
but not flag updates.
2023-03-24 16:09:15 +00:00
link2xt
84d79e1479 Do not use IDLE in test_mdn_asymmetric
Fixes test flakyness.
2023-03-24 16:08:58 +00:00
link2xt
83af248068 Turn more log messages into proper sentences. 2023-03-24 12:15:42 +00:00
link2xt
4f25edb1a1 Update OpenSSL to fix RUSTSEC-2023-0022
<https://rustsec.org/advisories/RUSTSEC-2023-0022>
2023-03-24 09:56:00 +00:00
link2xt
ded1634b7d python: look for "Marked messages ... as seen." by regexp
Tests reuse accounts, so UIDs may start from the number other than 1.
2023-03-24 09:43:59 +00:00
link2xt
635c73ffc6 python: use locally installed auditwheel
`auditwheel` is a part of manylinux images,
there is no need to create a virtual environment
and install it again.
2023-03-23 23:00:46 +00:00
link2xt
fcc1fe73be Do not use .wait_for_seen() in test_one_account_send_bcc_setting
.wait_for_seen() is unreliable, because sometimes Dovecot
sends only EXISTS to the IDLE connection, but not the FETCH.
Dovecot sends updates like FETCH only if some
connection has already observed the message in previous state
without the \Seen flag.

To avoid this race condition, wait until the core sets the flag,
then FETCH the message manually and check that the flag is set.
2023-03-23 22:57:35 +00:00
link2xt
fa278d50f7 Simplify layout of the deltachat-rpc-server crate 2023-03-23 22:10:28 +00:00
link2xt
2f02be4c64 ci: test the core on macOS 2023-03-23 20:46:58 +00:00
link2xt
7add1c116c Attempt to fix deltachat-rpc-server binary release uploads 2023-03-23 17:19:28 +00:00
link2xt
124a0e90e1 Release 1.112.0 2023-03-23 13:34:24 +00:00
Floris Bruynooghe
1716cdf51c ref(ffi): dc_receive_backup should block (#4211)
The documentation says this blocks.  This should block because it also
means the error reporting is more accurate by calling set_last_error
just before returning.
2023-03-23 14:15:34 +01:00
link2xt
3fdcffb314 Increase reference count before spawning background tasks in dc_receive_backup()
Merged PR <https://github.com/deltachat/deltachat-core-rust/pull/4206>
2023-03-23 08:54:33 +00:00
link2xt
f033aae25c Move most of the dc_receive_backup() into a safe function 2023-03-23 08:47:58 +00:00
Floris Bruynooghe
c42d942460 explicitly move for good measure 2023-03-23 08:47:58 +00:00
Floris Bruynooghe
0ba8201797 fix(dc_receive_backup): Increase refcount before spawn
Otherwise it is possible for the context that is used in the spawn to
be unreferenced.  Really this should be caught by the borrow checker
that ensures we only spawn things with a 'static lifetime, but we're
handling raw pointers so it doesn't.
2023-03-23 08:47:49 +00:00
iequidoo
87252ab053 cargo: bump async_zip from 0.0.9 to 0.0.11
Bumps [async_zip](https://github.com/Majored/rs-async-zip) from 0.0.9 to 0.0.11.
- [Release notes](https://github.com/Majored/rs-async-zip/releases)
- [Commits](https://github.com/Majored/rs-async-zip/compare/v0.0.9...v0.0.11)

---
updated-dependencies:
- dependency-name: async_zip
  dependency-type: direct:production
  update-type: version-update:semver-patch
...
2023-03-23 00:33:25 +00:00
link2xt
53eec521dc Make get_all_addresses_from_header non-generic
This saves 1287 lines according to `cargo llvm-lines --release`.
2023-03-22 23:51:41 +00:00
link2xt
238570a7b9 deltachat-ffi: update rand to 0.8.5 2023-03-22 23:37:01 +00:00
link2xt
043ae48806 Set pytest-timeout on async python tests 2023-03-22 20:41:17 +00:00
link2xt
fb88f2e6ab Reintroduce pytest-rerunfailures
Tests on GitHub Actions are very flaky recently.
2023-03-22 20:39:35 +00:00
link2xt
5db867cd1b Add IMAP_INBOX_IDLE event 2023-03-22 20:20:37 +00:00
B. Petersen
ec00c160c6 add missing define 2023-03-22 20:54:52 +01:00
Floris Bruynooghe
616eabc613 feat: Make the IoPausedGuard a simple sender (#4184)
This replaces the mechanism by which the IoPauseGuard makes sure the
IO scheduler is resumed: it really is a drop guard now by sending a
single message on drop.

This makes it not have to hold on to anything like the context so
makes it a lot easier to use.

The trade-off is that a long-running task is spawned when the guard is
created, this task needs to receive the message from the drop guard in
order for the scheduler to resume.
2023-03-22 17:42:21 +01:00
Floris Bruynooghe
89b32e02c5 deps(iroh): switch back to iroh main branch (#4202) 2023-03-22 16:05:55 +01:00
266 changed files with 25393 additions and 12160 deletions

8
.gitattributes vendored
View File

@@ -2,6 +2,14 @@
# ensures this even if the user has not set core.autocrlf.
* text=auto
# Checkout JavaScript files with LF line endings
# to prevent `prettier` from reporting errors on Windows.
*.js eol=lf
*.jsx eol=lf
*.ts eol=lf
*.tsx eol=lf
*.json eol=lf
# This directory contains email messages verbatim, and changing CRLF to
# LF will corrupt them.
test-data/** text=false

View File

@@ -5,5 +5,5 @@ updates:
schedule:
interval: "monthly"
commit-message:
prefix: "cargo"
prefix: "chore(cargo)"
open-pull-requests-limit: 50

26
.github/mergeable.yml vendored
View File

@@ -1,26 +0,0 @@
version: 2
mergeable:
- when: pull_request.*
name: "Changelog check"
validate:
- do: or
validate:
- do: description
must_include:
regex: "#skip-changelog"
- do: and
validate:
- do: dependent
changed:
file: "src/**"
required: ["CHANGELOG.md"]
- do: dependent
changed:
file: "deltachat-ffi/src/**"
required: ["CHANGELOG.md"]
fail:
- do: checks
status: "action_required"
payload:
title: Changelog might need an update
summary: "Check if CHANGELOG.md needs an update or add #skip-changelog to the PR description."

View File

@@ -1,3 +1,7 @@
# GitHub Actions workflow to
# lint Rust and Python code
# and run Rust tests, Python tests and async Python tests.
name: Rust CI
# Cancel previously started workflow runs
@@ -10,17 +14,17 @@ on:
pull_request:
push:
branches:
- master
- main
env:
RUSTFLAGS: -Dwarnings
jobs:
lint:
name: Rustfmt and Clippy
lint_rust:
name: Lint Rust
runs-on: ubuntu-latest
env:
RUSTUP_TOOLCHAIN: 1.68.0
RUSTUP_TOOLCHAIN: 1.74.1
steps:
- uses: actions/checkout@v3
- name: Install rustfmt and clippy
@@ -31,6 +35,8 @@ jobs:
run: cargo fmt --all -- --check
- name: Run clippy
run: scripts/clippy.sh
- name: Check
run: cargo check --workspace --all-targets --all-features
cargo_deny:
name: cargo deny
@@ -64,31 +70,24 @@ jobs:
- name: Rustdoc
run: cargo doc --document-private-items --no-deps
build_and_test:
name: Build and test
rust_tests:
name: Rust tests
strategy:
fail-fast: false
matrix:
include:
# Currently used Rust version.
- os: ubuntu-latest
rust: 1.68.0
python: 3.9
rust: 1.74.1
- os: windows-latest
rust: 1.68.0
python: false # Python bindings compilation on Windows is not supported.
rust: 1.74.1
- os: macos-latest
rust: 1.74.1
# Minimum Supported Rust Version = 1.64.0
#
# Minimum Supported Python Version = 3.7
# This is the minimum version for which manylinux Python wheels are
# built.
# Minimum Supported Rust Version = 1.70.0
- os: ubuntu-latest
rust: 1.64.0
python: 3.7
rust: 1.70.0
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@master
- uses: actions/checkout@v3
- name: Install Rust ${{ matrix.rust }}
run: rustup toolchain install --profile minimal ${{ matrix.rust }}
@@ -97,64 +96,184 @@ jobs:
- name: Cache rust cargo artifacts
uses: swatinem/rust-cache@v2
- name: Check
run: cargo check --workspace --bins --examples --tests --benches
- name: Tests
env:
RUST_BACKTRACE: 1
run: cargo test --workspace
- name: Test cargo vendor
run: cargo vendor
c_library:
name: Build C library
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Cache rust cargo artifacts
uses: swatinem/rust-cache@v2
- name: Build C library
run: cargo build -p deltachat_ffi --features jsonrpc
- name: Upload C library
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.os }}-libdeltachat.a
path: target/debug/libdeltachat.a
retention-days: 1
rpc_server:
name: Build deltachat-rpc-server
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Cache rust cargo artifacts
uses: swatinem/rust-cache@v2
- name: Build deltachat-rpc-server
run: cargo build -p deltachat-rpc-server
- name: Upload deltachat-rpc-server
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.os }}-deltachat-rpc-server
path: ${{ matrix.os == 'windows-latest' && 'target/debug/deltachat-rpc-server.exe' || 'target/debug/deltachat-rpc-server' }}
retention-days: 1
python_lint:
name: Python lint
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v3
- name: Install tox
run: pip install tox
- name: Lint Python bindings
working-directory: python
run: tox -e lint
- name: Lint deltachat-rpc-client
working-directory: deltachat-rpc-client
run: tox -e lint
cffi_python_tests:
name: CFFI Python tests
needs: ["c_library", "python_lint"]
strategy:
fail-fast: false
matrix:
include:
# Currently used Rust version.
- os: ubuntu-latest
python: 3.12
- os: macos-latest
python: 3.12
# PyPy tests
- os: ubuntu-latest
python: pypy3.10
- os: macos-latest
python: pypy3.10
# Minimum Supported Python Version = 3.7
# This is the minimum version for which manylinux Python wheels are
# built. Test it with minimum supported Rust version.
- os: ubuntu-latest
python: 3.7
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Download libdeltachat.a
uses: actions/download-artifact@v3
with:
name: ${{ matrix.os }}-libdeltachat.a
path: target/debug
- name: Install python
if: ${{ matrix.python }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}
- name: Install tox
if: ${{ matrix.python }}
run: pip install tox
- name: Build C library
if: ${{ matrix.python }}
run: cargo build -p deltachat_ffi --features jsonrpc
- name: Run python tests
if: ${{ matrix.python }}
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
CHATMAIL_DOMAIN: ${{ secrets.CHATMAIL_DOMAIN }}
DCC_RS_TARGET: debug
DCC_RS_DEV: ${{ github.workspace }}
working-directory: python
run: tox -e lint,mypy,doc,py3
run: tox -e mypy,doc,py
- name: Build deltachat-rpc-server
if: ${{ matrix.python }}
run: cargo build -p deltachat-rpc-server
rpc_python_tests:
name: JSON-RPC Python tests
needs: ["python_lint", "rpc_server"]
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
python: 3.12
- os: macos-latest
python: 3.12
- os: windows-latest
python: 3.12
- name: Add deltachat-rpc-server to path
if: ${{ matrix.python }}
run: echo ${{ github.workspace }}/target/debug >> $GITHUB_PATH
# PyPy tests
- os: ubuntu-latest
python: pypy3.10
- os: macos-latest
python: pypy3.10
- name: Run deltachat-rpc-client tests
if: ${{ matrix.python }}
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
working-directory: deltachat-rpc-client
run: tox -e py3,lint
# Minimum Supported Python Version = 3.7
- os: ubuntu-latest
python: 3.7
- name: Install pypy
if: ${{ matrix.python }}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Install python
uses: actions/setup-python@v4
with:
python-version: "pypy${{ matrix.python }}"
python-version: ${{ matrix.python }}
- name: Run pypy tests
if: ${{ matrix.python }}
- name: Install tox
run: pip install tox
- name: Download deltachat-rpc-server
uses: actions/download-artifact@v3
with:
name: ${{ matrix.os }}-deltachat-rpc-server
path: target/debug
- name: Make deltachat-rpc-server executable
if: ${{ matrix.os != 'windows-latest' }}
run: chmod +x target/debug/deltachat-rpc-server
- name: Add deltachat-rpc-server to path
if: ${{ matrix.os != 'windows-latest' }}
run: echo ${{ github.workspace }}/target/debug >> $GITHUB_PATH
- name: Add deltachat-rpc-server to path
if: ${{ matrix.os == 'windows-latest' }}
run: |
"${{ github.workspace }}/target/debug" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- name: Run deltachat-rpc-client tests
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
DCC_RS_TARGET: debug
DCC_RS_DEV: ${{ github.workspace }}
working-directory: python
run: tox -e pypy3
CHATMAIL_DOMAIN: ${{ secrets.CHATMAIL_DOMAIN }}
working-directory: deltachat-rpc-client
run: tox -e py

View File

@@ -1,4 +1,10 @@
# Manually triggered action to build deltachat-rpc-server binaries.
# GitHub Actions workflow
# to build `deltachat-rpc-server` binaries
# and upload them to the release.
#
# The workflow is automatically triggered on releases.
# It can also be triggered manually
# to produce binary artifacts for testing.
name: Build deltachat-rpc-server binaries
@@ -15,33 +21,22 @@ jobs:
# Build a version statically linked against musl libc
# to avoid problems with glibc version incompatibility.
build_linux:
name: Cross-compile deltachat-rpc-server for x86_64, aarch64 and armv7 Linux
name: Cross-compile deltachat-rpc-server for x86_64, i686, aarch64 and armv7 Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Build
- name: Install ziglang
run: pip install wheel ziglang==0.11.0
- name: Build deltachat-rpc-server binaries
run: sh scripts/zig-rpc-server.sh
- name: Upload x86_64 binary
- name: Upload dist directory with Linux binaries
uses: actions/upload-artifact@v3
with:
name: deltachat-rpc-server-x86_64
path: target/x86_64-unknown-linux-musl/release/deltachat-rpc-server
if-no-files-found: error
- name: Upload aarch64 binary
uses: actions/upload-artifact@v3
with:
name: deltachat-rpc-server-aarch64
path: target/aarch64-unknown-linux-musl/release/deltachat-rpc-server
if-no-files-found: error
- name: Upload armv7 binary
uses: actions/upload-artifact@v3
with:
name: deltachat-rpc-server-armv7
path: target/armv7-unknown-linux-musleabihf/release/deltachat-rpc-server
name: linux
path: dist/
if-no-files-found: error
build_windows:
@@ -77,42 +72,89 @@ jobs:
path: target/${{ matrix.target}}/release/${{ matrix.path }}
if-no-files-found: error
build_macos:
name: Build deltachat-rpc-server for macOS
strategy:
fail-fast: false
matrix:
include:
- arch: x86_64
- arch: aarch64
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- name: Setup rust target
run: rustup target add ${{ matrix.arch }}-apple-darwin
- name: Build
run: cargo build --release --package deltachat-rpc-server --target ${{ matrix.arch }}-apple-darwin --features vendored
- name: Upload binary
uses: actions/upload-artifact@v3
with:
name: deltachat-rpc-server-${{ matrix.arch }}-macos
path: target/${{ matrix.arch }}-apple-darwin/release/deltachat-rpc-server
if-no-files-found: error
publish:
name: Upload binaries to the release
needs: ["build_linux", "build_windows"]
name: Build wheels and upload binaries to the release
needs: ["build_linux", "build_windows", "build_macos"]
permissions:
contents: write
runs-on: "ubuntu-latest"
steps:
- name: Download deltachat-rpc-server-x86_64
uses: "actions/download-artifact@v3"
with:
name: "deltachat-rpc-server-x86_64"
path: "dist/deltachat-rpc-server-x86_64"
- uses: actions/checkout@v3
- name: Download deltachat-rpc-server-aarch64
uses: "actions/download-artifact@v3"
- name: Download Linux binaries
uses: actions/download-artifact@v3
with:
name: "deltachat-rpc-server-aarch64"
path: "dist/deltachat-rpc-server-aarch64"
name: linux
path: dist/
- name: Download deltachat-rpc-server-armv7
uses: "actions/download-artifact@v3"
- name: Download win32 binary
uses: actions/download-artifact@v3
with:
name: "deltachat-rpc-server-armv7"
path: "dist/deltachat-rpc-server-armv7"
name: deltachat-rpc-server-win32.exe
path: deltachat-rpc-server-win32.exe.d
- name: Download deltachat-rpc-server-win32.exe
uses: "actions/download-artifact@v3"
- name: Download win64 binary
uses: actions/download-artifact@v3
with:
name: "deltachat-rpc-server-win32.exe"
path: "dist/deltachat-rpc-server-win32.exe"
name: deltachat-rpc-server-win64.exe
path: deltachat-rpc-server-win64.exe.d
- name: Download deltachat-rpc-server-win64.exe
uses: "actions/download-artifact@v3"
- name: Download macOS binary for x86_64
uses: actions/download-artifact@v3
with:
name: "deltachat-rpc-server-win64.exe"
path: "dist/deltachat-rpc-server-win64.exe"
name: deltachat-rpc-server-x86_64-macos
path: deltachat-rpc-server-x86_64-macos.d
- name: Download macOS binary for aarch64
uses: actions/download-artifact@v3
with:
name: deltachat-rpc-server-aarch64-macos
path: deltachat-rpc-server-aarch64-macos.d
- name: Flatten dist/ directory
run: |
mv deltachat-rpc-server-win32.exe.d/deltachat-rpc-server.exe dist/deltachat-rpc-server-win32.exe
mv deltachat-rpc-server-win64.exe.d/deltachat-rpc-server.exe dist/deltachat-rpc-server-win64.exe
mv deltachat-rpc-server-x86_64-macos.d/deltachat-rpc-server dist/deltachat-rpc-server-x86_64-macos
mv deltachat-rpc-server-aarch64-macos.d/deltachat-rpc-server dist/deltachat-rpc-server-aarch64-macos
# Python 3.11 is needed for tomllib used in scripts/wheel-rpc-server.py
- name: Install python 3.12
uses: actions/setup-python@v4
with:
python-version: 3.12
- name: Install wheel
run: pip install wheel
- name: Build deltachat-rpc-server Python wheels and source package
run: scripts/wheel-rpc-server.py
- name: List downloaded artifacts
run: ls -l dist/
@@ -123,4 +165,4 @@ jobs:
run: |
gh release upload ${{ github.ref_name }} \
--repo ${{ github.repository }} \
dist/deltachat-rpc-server-*
dist/*

View File

@@ -1,3 +1,6 @@
# GitHub Actions workflow
# to automatically approve PRs made by Dependabot.
name: Dependabot auto-approve
on: pull_request

View File

@@ -17,7 +17,7 @@ jobs:
uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
node-version: "18"
- name: Get tag
id: tag
uses: dawidd6/action-get-tag@v1
@@ -38,13 +38,12 @@ jobs:
node --version
echo $DELTACHAT_JSONRPC_TAR_GZ
- name: Install dependencies without running scripts
run: |
cd deltachat-jsonrpc/typescript
npm install --ignore-scripts
working-directory: deltachat-jsonrpc/typescript
run: npm install --ignore-scripts
- name: Package
shell: bash
working-directory: deltachat-jsonrpc/typescript
run: |
cd deltachat-jsonrpc/typescript
npm run build
npm pack .
ls -lah

View File

@@ -2,9 +2,9 @@ name: JSON-RPC API Test
on:
push:
branches: [master]
branches: [main]
pull_request:
branches: [master]
branches: [main]
env:
CARGO_TERM_COLOR: always
@@ -15,31 +15,26 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node.js 16.x
- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: 16.x
node-version: 18.x
- name: Add Rust cache
uses: Swatinem/rust-cache@v2
- name: npm install
run: |
cd deltachat-jsonrpc/typescript
npm install
working-directory: deltachat-jsonrpc/typescript
run: npm install
- name: Build TypeScript, run Rust tests, generate bindings
run: |
cd deltachat-jsonrpc/typescript
npm run build
working-directory: deltachat-jsonrpc/typescript
run: npm run build
- name: Run integration tests
run: |
cd deltachat-jsonrpc/typescript
npm run test
working-directory: deltachat-jsonrpc/typescript
run: npm run test
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
CHATMAIL_DOMAIN: ${{ secrets.CHATMAIL_DOMAIN }}
- name: make sure websocket server version still builds
run: |
cd deltachat-jsonrpc
cargo build --bin deltachat-jsonrpc-server --features webserver
working-directory: deltachat-jsonrpc
run: cargo build --bin deltachat-jsonrpc-server --features webserver
- name: Run linter
run: |
cd deltachat-jsonrpc/typescript
npm run prettier:check
working-directory: deltachat-jsonrpc/typescript
run: npm run prettier:check

View File

@@ -1,31 +0,0 @@
# documentation: https://github.com/deltachat/sysadmin/tree/master/download.delta.chat
name: Delete node PR previews
on:
pull_request:
types: [closed]
jobs:
delete:
runs-on: ubuntu-latest
steps:
- name: Get Pull Request ID
id: getid
run: |
export PULLREQUEST_ID=$(jq .number < $GITHUB_EVENT_PATH)
echo "prid=$PULLREQUEST_ID" >> $GITHUB_OUTPUT
- name: Renaming
run: |
# create empty file to copy it over the outdated deliverable on download.delta.chat
echo "This preview build is outdated and has been removed." > empty
cp empty deltachat-node-${{ steps.getid.outputs.prid }}.tar.gz
- name: Replace builds with dummy files
uses: horochx/deploy-via-scp@v1.0.1
with:
user: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
host: "download.delta.chat"
port: 22
local: "deltachat-node-${{ steps.getid.outputs.prid }}.tar.gz"
remote: "/var/www/html/download/node/preview/"

View File

@@ -1,9 +1,14 @@
# GitHub Actions workflow to build
# Node.js bindings documentation
# and upload it to the web server.
# Built documentation is available at <https://js.delta.chat/>
name: Generate & upload node.js documentation
on:
push:
branches:
- master
- main
jobs:
generate:
@@ -11,14 +16,14 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Use Node.js 16.x
- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: 16.x
node-version: 18.x
- name: npm install and generate documentation
working-directory: node
run: |
cd node
npm i --ignore-scripts
npx typedoc
mv docs js

View File

@@ -12,13 +12,13 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-20.04, macos-latest, windows-latest]
os: [macos-latest, windows-latest]
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
node-version: "18"
- name: System info
run: |
rustc -vV
@@ -46,13 +46,12 @@ jobs:
- name: Install dependencies & build
if: steps.cache.outputs.cache-hit != 'true'
run: |
cd node
npm install --verbose
working-directory: node
run: npm install --verbose
- name: Build Prebuild
working-directory: node
run: |
cd node
npm run prebuildify
tar -zcvf "${{ matrix.os }}.tar.gz" -C prebuilds .
@@ -62,10 +61,79 @@ jobs:
name: ${{ matrix.os }}
path: node/${{ matrix.os }}.tar.gz
prebuild-linux:
name: Prebuild Linux
runs-on: ubuntu-latest
# Build Linux prebuilds inside a container with old glibc for backwards compatibility.
# Debian 10 contained glibc 2.28: https://packages.debian.org/buster/libc6
container: debian:10
steps:
# Working directory is owned by 1001:1001 by default.
# Change it to our user.
- name: Change working directory owner
run: chown root:root .
- name: Checkout
uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "18"
- run: apt-get update
# Python is needed for node-gyp
- name: Install curl, python and compilers
run: apt-get install -y curl build-essential python3
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: System info
run: |
rustc -vV
rustup -vV
cargo -vV
npm --version
node --version
- name: Cache node modules
uses: actions/cache@v3
with:
path: |
${{ env.APPDATA }}/npm-cache
~/.npm
key: ${{ matrix.os }}-node-${{ hashFiles('**/package.json') }}
- name: Cache cargo index
uses: actions/cache@v3
with:
path: |
~/.cargo/registry/
~/.cargo/git
target
key: ${{ matrix.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}-2
- name: Install dependencies & build
if: steps.cache.outputs.cache-hit != 'true'
working-directory: node
run: npm install --verbose
- name: Build Prebuild
working-directory: node
run: |
npm run prebuildify
tar -zcvf "linux.tar.gz" -C prebuilds .
- name: Upload Prebuild
uses: actions/upload-artifact@v3
with:
name: linux
path: node/linux.tar.gz
pack-module:
needs: prebuild
needs: [prebuild, prebuild-linux]
name: Package deltachat-node and upload to download.delta.chat
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Install tree
run: sudo apt install tree
@@ -73,7 +141,7 @@ jobs:
uses: actions/checkout@v3
- uses: actions/setup-node@v2
with:
node-version: "16"
node-version: "18"
- name: Get tag
id: tag
uses: dawidd6/action-get-tag@v1
@@ -96,10 +164,10 @@ jobs:
npm --version
node --version
echo $DELTACHAT_NODE_TAR_GZ
- name: Download Ubuntu prebuild
- name: Download Linux prebuild
uses: actions/download-artifact@v1
with:
name: ubuntu-20.04
name: linux
- name: Download macOS prebuild
uses: actions/download-artifact@v1
with:
@@ -111,11 +179,11 @@ jobs:
- shell: bash
run: |
mkdir node/prebuilds
tar -xvzf ubuntu-20.04/ubuntu-20.04.tar.gz -C node/prebuilds
tar -xvzf linux/linux.tar.gz -C node/prebuilds
tar -xvzf macos-latest/macos-latest.tar.gz -C node/prebuilds
tar -xvzf windows-latest/windows-latest.tar.gz -C node/prebuilds
tree node/prebuilds
rm -rf ubuntu-20.04 macos-latest windows-latest
rm -rf linux macos-latest windows-latest
- name: Install dependencies without running scripts
run: |
npm install --ignore-scripts

View File

@@ -1,3 +1,6 @@
# GitHub Actions workflow
# to test Node.js bindings.
name: "node.js tests"
# Cancel previously started workflow runs
@@ -10,7 +13,7 @@ on:
pull_request:
push:
branches:
- master
- main
jobs:
tests:
@@ -24,7 +27,7 @@ jobs:
uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "16"
node-version: "18"
- name: System info
run: |
rustc -vV
@@ -52,25 +55,13 @@ jobs:
- name: Install dependencies & build
if: steps.cache.outputs.cache-hit != 'true'
run: |
cd node
npm install --verbose
working-directory: node
run: npm install --verbose
- name: Test
timeout-minutes: 10
if: runner.os != 'Windows'
run: |
cd node
npm run test
working-directory: node
run: npm run test
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
NODE_OPTIONS: "--force-node-api-uncaught-exceptions-policy=true"
- name: Run tests on Windows, except lint
timeout-minutes: 10
if: runner.os == 'Windows'
run: |
cd node
npm run test:mocha
env:
DCC_NEW_TMP_EMAIL: ${{ secrets.DCC_NEW_TMP_EMAIL }}
CHATMAIL_DOMAIN: ${{ secrets.CHATMAIL_DOMAIN }}
NODE_OPTIONS: "--force-node-api-uncaught-exceptions-policy=true"

View File

@@ -1,4 +1,5 @@
# Manually triggered action to build a Windows repl.exe which users can
# Manually triggered GitHub Actions workflow
# to build a Windows repl.exe which users can
# download to debug complex bugs.
name: Build Windows REPL .exe

View File

@@ -3,8 +3,7 @@ name: Build & Deploy Documentation on rs.delta.chat
on:
push:
branches:
- master
- docs-gh-action
- main
jobs:
build:

View File

@@ -1,10 +1,13 @@
# GitHub Actions workflow
# to build `deltachat_fii` crate documentation
# and upload it to <https://cffi.delta.chat/>
name: Build & Deploy Documentation on cffi.delta.chat
on:
push:
branches:
- master
- docs-gh-action
- main
jobs:
build:

View File

@@ -0,0 +1,25 @@
name: Build & Deploy Documentation on py.delta.chat
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Fetch history to calculate VCS version number.
- name: Build Python documentation
run: scripts/build-python-docs.sh
- name: Upload to py.delta.chat
uses: up9cloud/action-rsync@v1.3
env:
USER: delta
KEY: ${{ secrets.CODESPEAK_KEY }}
HOST: "lists.codespeak.net"
SOURCE: "dist/html/"
TARGET: "/home/delta/build/master"

4
.gitignore vendored
View File

@@ -1,6 +1,7 @@
/target
**/*.rs.bk
/build
/dist
# ignore vi temporaries
*~
@@ -18,6 +19,9 @@ python/.eggs
__pycache__
python/src/deltachat/capi*.so
python/.venv/
python/venv/
venv/
env/
python/liveconfig*

File diff suppressed because it is too large Load Diff

126
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,126 @@
# Contributing guidelines
## Reporting bugs
If you found a bug, [report it on GitHub](https://github.com/deltachat/deltachat-core-rust/issues).
If the bug you found is specific to
[Android](https://github.com/deltachat/deltachat-android/issues),
[iOS](https://github.com/deltachat/deltachat-ios/issues) or
[Desktop](https://github.com/deltachat/deltachat-desktop/issues),
report it to the corresponding repository.
## Proposing features
If you have a feature request, create a new topic on the [forum](https://support.delta.chat/).
## Contributing code
If you want to contribute a code, [open a Pull Request](https://github.com/deltachat/deltachat-core-rust/pulls).
If you have write access to the repository,
push a branch named `<username>/<feature>`
so it is clear who is responsible for the branch,
and open a PR proposing to merge the change.
Otherwise fork the repository and create a branch in your fork.
You can find the list of good first issues
and a link to this guide
on the contributing page: <https://github.com/deltachat/deltachat-core-rust/contribute>
### Coding conventions
We format the code using `rustfmt`. Run `cargo fmt` prior to committing the code.
Run `scripts/clippy.sh` to check the code for common mistakes with [Clippy].
Commit messages follow the [Conventional Commits] notation.
We use [git-cliff] to generate the changelog from commit messages before the release.
With **`git cliff --unreleased`**, you can check how the changelog entry for your commit will look.
The following prefix types are used:
- `feat`: Features, e.g. "feat: Pause IO for BackupProvider". If you are unsure what's the category of your commit, you can often just use `feat`.
- `fix`: Bug fixes, e.g. "fix: delete `smtp` rows when message sending is cancelled"
- `api`: API changes, e.g. "api(rust): add `get_msg_read_receipts(context, msg_id)`"
- `refactor`: Refactorings, e.g. "refactor: iterate over `msg_ids` without `.iter()`"
- `perf`: Performance improvements, e.g. "perf: improve SQLite performance with `PRAGMA synchronous=normal`"
- `test`: Test changes and improvements to the testing framework.
- `build`: Build system and tool configuration changes, e.g. "build(git-cliff): put "ci" commits into "CI" section of changelog"
- `ci`: CI configuration changes, e.g. "ci: limit artifact retention time for `libdeltachat.a` to 1 day"
- `docs`: Documentation changes, e.g. "docs: add contributing guidelines"
- `chore`: miscellaneous tasks, e.g. "chore: add `.DS_Store` to `.gitignore`"
Release preparation commits are marked as "chore(release): prepare for vX.Y.Z".
If you intend to squash merge the PR from the web interface,
make sure the PR title follows the conventional commits notation
as it will end up being a commit title.
Otherwise make sure each commit title follows the conventional commit notation.
#### Breaking Changes
Use a `!` to mark breaking changes, e.g. "api!: Remove `dc_chat_can_send`".
Alternatively, breaking changes can go into the commit description, e.g.:
```
fix: Fix race condition and db corruption when a message was received during backup
BREAKING CHANGE: You have to call `dc_stop_io()`/`dc_start_io()` before/after `dc_imex(DC_IMEX_EXPORT_BACKUP)`
```
#### Multiple Changes in one PR
If you have multiple changes in one PR, create multiple conventional commits, and then do a rebase merge. Otherwise, you should usually do a squash merge.
[Clippy]: https://doc.rust-lang.org/clippy/
[Conventional Commits]: https://www.conventionalcommits.org/
[git-cliff]: https://git-cliff.org/
### Errors
Delta Chat core mostly uses [`anyhow`](https://docs.rs/anyhow/) errors.
When using [`Context`](https://docs.rs/anyhow/latest/anyhow/trait.Context.html),
capitalize it but do not add a full stop as the contexts will be separated by `:`.
For example:
```
.with_context(|| format!("Unable to trash message {msg_id}"))
```
All errors should be handled in one of these ways:
- With `if let Err() =` (incl. logging them into `warn!()`/`err!()`).
- With `.log_err().ok()`.
- Bubbled up with `?`.
`backtrace` feature is enabled for `anyhow` crate
and `debug = 1` option is set in the test profile.
This allows to run `RUST_BACKTRACE=1 cargo test`
and get a backtrace with line numbers in resultified tests
which return `anyhow::Result`.
### Logging
For logging, use `info!`, `warn!` and `error!` macros.
Log messages should be capitalized and have a full stop in the end. For example:
```
info!(context, "Ignoring addition of {added_addr:?} to {chat_id}.");
```
Format anyhow errors with `{:#}` to print all the contexts like this:
```
error!(context, "Failed to set selfavatar timestamp: {err:#}.");
```
### Reviewing
Once a PR has an approval and passes CI, it can be merged.
PRs from a branch created in the main repository, i.e. authored by those who have write access, are merged by their authors.
This is to ensure that PRs are merged as intended by the author,
e.g. as a squash merge, by rebasing from the web interface or manually from the command line.
If you do not have access to the repository and created a PR from a fork,
ask the maintainers to merge the PR and say how it should be merged.
## Other ways to contribute
For other ways to contribute, refer to the [website](https://delta.chat/en/contribute).

3152
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,9 @@
[package]
name = "deltachat"
version = "1.111.0"
version = "1.132.1"
edition = "2021"
license = "MPL-2.0"
rust-version = "1.64"
rust-version = "1.70"
[profile.dev]
debug = 0
@@ -11,6 +11,10 @@ panic = 'abort'
opt-level = 1
[profile.test]
# Make anyhow `backtrace` feature useful.
# With `debug = 0` there are no line numbers in the backtrace
# produced with RUST_BACKTRACE=1.
debug = 1
opt-level = 0
# Always optimize dependencies.
@@ -23,11 +27,11 @@ opt-level = "z"
lto = true
panic = 'abort'
opt-level = "z"
codegen-units = 1
strip = true
[patch.crates-io]
default-net = { git = "https://github.com/dignifiedquire/default-net.git", branch="feat-android" }
quinn-udp = { git = "https://github.com/quinn-rs/quinn", branch="main" }
quinn-proto = { git = "https://github.com/quinn-rs/quinn", branch="main" }
imap-proto = { git = "https://github.com/djc/tokio-imap.git", rev = "01ff256a7e42a9f7d2732706f8b71a16ce93427e" }
[dependencies]
deltachat_derive = { path = "./deltachat_derive" }
@@ -35,75 +39,80 @@ format-flowed = { path = "./format-flowed" }
ratelimit = { path = "./deltachat-ratelimit" }
anyhow = "1"
async-channel = "1.8.0"
async-imap = { git = "https://github.com/async-email/async-imap", branch = "master", default-features = false, features = ["runtime-tokio"] }
async-channel = "2.0.0"
async-imap = { version = "0.9.5", default-features = false, features = ["runtime-tokio"] }
async-native-tls = { version = "0.5", default-features = false, features = ["runtime-tokio"] }
async-smtp = { version = "0.9", default-features = false, features = ["runtime-tokio"] }
async_zip = { version = "0.0.9", default-features = false, features = ["deflate"] }
async_zip = { version = "0.0.12", default-features = false, features = ["deflate", "fs"] }
backtrace = "0.3"
base64 = "0.21"
bitflags = "1.3"
brotli = { version = "3.4", default-features=false, features = ["std"] }
chrono = { version = "0.4", default-features=false, features = ["clock", "std"] }
email = { git = "https://github.com/deltachat/rust-email", branch = "master" }
encoded-words = { git = "https://github.com/async-email/encoded-words", branch = "master" }
escaper = "0.1"
fast-socks5 = "0.8"
fast-socks5 = "0.9"
fd-lock = "4"
futures = "0.3"
futures-lite = "1.12.0"
futures-lite = "2.0.0"
hex = "0.4.0"
hickory-resolver = "0.24"
humansize = "2"
image = { version = "0.24.5", default-features=false, features = ["gif", "jpeg", "ico", "png", "pnm", "webp", "bmp"] }
# iroh = { version = "0.3.0", default-features = false }
iroh = { git = 'https://github.com/n0-computer/iroh', branch = "flub/ticket-multiple-addrs" }
image = { version = "0.24.7", default-features=false, features = ["gif", "jpeg", "ico", "png", "pnm", "webp", "bmp"] }
iroh = { git = "https://github.com/n0-computer/iroh", branch = "maint-0.4", default-features = false }
kamadak-exif = "0.5"
lettre_email = { git = "https://github.com/deltachat/lettre", branch = "master" }
libc = "0.2"
mailparse = "0.14"
num_cpus = "1.15"
num-derive = "0.3"
mime = "0.3.17"
num_cpus = "1.16"
num-derive = "0.4"
num-traits = "0.2"
once_cell = "1.17.0"
percent-encoding = "2.2"
once_cell = "1.18.0"
percent-encoding = "2.3"
parking_lot = "0.12"
pgp = { version = "0.9", default-features = false }
pretty_env_logger = { version = "0.4", optional = true }
pgp = { version = "0.10", default-features = false }
pin-project = "1"
pretty_env_logger = { version = "0.5", optional = true }
qrcodegen = "1.7.0"
quick-xml = "0.27"
quick-xml = "0.31"
rand = "0.8"
regex = "1.7"
reqwest = { version = "0.11.14", features = ["json"] }
rusqlite = { version = "0.28", features = ["sqlcipher"] }
regex = "1.9"
reqwest = { version = "0.11.20", features = ["json"] }
rusqlite = { version = "0.30", features = ["sqlcipher"] }
rust-hsluv = "0.1"
sanitize-filename = "0.4"
sanitize-filename = "0.5"
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
sha-1 = "0.10"
sha2 = "0.10"
smallvec = "1"
strum = "0.24"
strum_macros = "0.24"
strum = "0.25"
strum_macros = "0.25"
tagger = "4.3.4"
textwrap = "0.16.0"
thiserror = "1"
tokio-io-timeout = "1.2.0"
tokio-stream = { version = "0.1.11", features = ["fs"] }
tokio-tar = { version = "0.3" } # TODO: integrate tokio into async-tar
tokio = { version = "1", features = ["fs", "rt-multi-thread", "macros"] }
toml = "0.7"
trust-dns-resolver = "0.22"
tokio-io-timeout = "1.2.0"
tokio-stream = { version = "0.1.14", features = ["fs"] }
tokio-tar = { version = "0.3" } # TODO: integrate tokio into async-tar
tokio-util = "0.7.9"
toml = "0.8"
url = "2"
uuid = { version = "1", features = ["serde", "v4"] }
[dev-dependencies]
ansi_term = "0.12.0"
criterion = { version = "0.4.0", features = ["async_tokio"] }
futures-lite = "1.12"
anyhow = { version = "1", features = ["backtrace"] } # Enable `backtrace` feature in tests.
criterion = { version = "0.5.1", features = ["async_tokio"] }
futures-lite = "2.0.0"
log = "0.4"
pretty_env_logger = "0.4"
pretty_env_logger = "0.5"
proptest = { version = "1", default-features = false, features = ["std"] }
tempfile = "3"
testdir = "0.7.2"
testdir = "0.9.0"
tokio = { version = "1", features = ["parking_lot", "rt-multi-thread", "macros"] }
pretty_assertions = "1.3.0"
[workspace]
members = [
@@ -116,11 +125,6 @@ members = [
"format-flowed",
]
[[example]]
name = "simple"
path = "examples/simple.rs"
[[bench]]
name = "create_account"
harness = false

View File

@@ -361,7 +361,7 @@ Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE

View File

@@ -1,8 +1,16 @@
# Delta Chat Rust
<p align="center">
<img alt="Delta Chat Logo" height="200px" src="https://raw.githubusercontent.com/deltachat/deltachat-pages/master/assets/blog/rust-delta.png">
</p>
> Deltachat-core written in Rust
<p align="center">
<a href="https://github.com/deltachat/deltachat-core-rust/actions/workflows/ci.yml">
<img alt="Rust CI" src="https://github.com/deltachat/deltachat-core-rust/actions/workflows/ci.yml/badge.svg">
</a>
</p>
[![Rust CI](https://github.com/deltachat/deltachat-core-rust/actions/workflows/ci.yml/badge.svg)](https://github.com/deltachat/deltachat-core-rust/actions/workflows/ci.yml)
<p align="center">
The core library for Delta Chat, written in Rust
</p>
## Installing Rust and Cargo
@@ -167,8 +175,8 @@ Language bindings are available for:
- **C** \[[📂 source](./deltachat-ffi) | [📚 docs](https://c.delta.chat)\]
- **Node.js**
- over cffi (legacy): \[[📂 source](./node) | [📦 npm](https://www.npmjs.com/package/deltachat-node) | [📚 docs](https://js.delta.chat)\]
- over jsonrpc built with napi.rs: \[[📂 source](https://github.com/deltachat/napi-jsonrpc) | [📦 npm](https://www.npmjs.com/package/@deltachat/napi-jsonrpc)\]
- over cffi: \[[📂 source](./node) | [📦 npm](https://www.npmjs.com/package/deltachat-node) | [📚 docs](https://js.delta.chat)\]
- over jsonrpc built with napi.rs (experimental): \[[📂 source](https://github.com/deltachat/napi-jsonrpc) | [📦 npm](https://www.npmjs.com/package/@deltachat/napi-jsonrpc)\]
- **Python** \[[📂 source](./python) | [📦 pypi](https://pypi.org/project/deltachat) | [📚 docs](https://py.delta.chat)\]
- **Go**
- over jsonrpc: \[[📂 source](https://github.com/deltachat/deltachat-rpc-client-go/)\]

21
RELEASE.md Normal file
View File

@@ -0,0 +1,21 @@
# Releasing a new version of DeltaChat core
For example, to release version 1.116.0 of the core, do the following steps.
1. Resolve all [blocker issues](https://github.com/deltachat/deltachat-core-rust/labels/blocker).
2. Run `npm run build:core:constants` in the root of the repository
and commit generated `node/constants.js`, `node/events.js` and `node/lib/constants.js`.
3. Update the changelog: `git cliff --unreleased --tag 1.116.0 --prepend CHANGELOG.md` or `git cliff -u -t 1.116.0 -p CHANGELOG.md`.
4. Update the version by running `scripts/set_core_version.py 1.116.0`.
5. Commit the changes as `chore(release): prepare for 1.116.0`.
Optionally, use a separate branch like `prep-1.116.0` for this commit and open a PR for review.
6. Tag the release: `git tag -a v1.116.0`.
7. Push the release tag: `git push origin v1.116.0`.
8. Create a GitHub release: `gh release create v1.116.0 -n ''`.

View File

@@ -8,7 +8,8 @@ async fn create_accounts(n: u32) {
let dir = tempdir().unwrap();
let p: PathBuf = dir.path().join("accounts");
let mut accounts = Accounts::new(p.clone()).await.unwrap();
let writable = true;
let mut accounts = Accounts::new(p.clone(), writable).await.unwrap();
for expected_id in 2..n {
let id = accounts.add_account().await.unwrap();

79
cliff.toml Normal file
View File

@@ -0,0 +1,79 @@
# configuration file for git-cliff
# see https://git-cliff.org/docs/configuration/
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = false
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/deltachat/deltachat-core-rust/pull/${2}))"}, # replace pull request / issue numbers
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "Features / Changes"},
{ message = "^fix", group = "Fixes"},
{ message = "^api", group = "API-Changes" },
{ message = "^refactor", group = "Refactor"},
{ message = "^perf", group = "Performance"},
{ message = "^test", group = "Tests"},
{ message = "^style", group = "Styling"},
{ message = "^chore\\(release\\): prepare for", skip = true},
{ message = "^chore", group = "Miscellaneous Tasks"},
{ message = "^build", group = "Build system"},
{ message = "^docs", group = "Documentation"},
{ message = "^ci", group = "CI"},
{ message = ".*", group = "Other"},
# { body = ".*security", group = "Security"},
]
# protect breaking changes from being skipped due to matching a skipping commit_parser
protect_breaking_commits = true
# filter out the commits that are not matched by commit parsers
filter_commits = true
# glob pattern for matching git tags
tag_pattern = "v[0-9]*"
# regex for skipping tags
#skip_tags = "v0.1.0-beta.1"
# regex for ignoring tags
ignore_tags = ""
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
# limit the number of commits included in the changelog.
# limit_commits = 42
[changelog]
# changelog header
header = """
# Changelog\n
"""
# template for the changelog body
# https://keats.github.io/tera/docs/#templates
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {% if commit.breaking %}[**breaking**] {% endif %}\
{% if commit.scope %}{{ commit.scope }}: {% endif %}\
{{ commit.message | upper_first }}.\
{% if commit.footers is defined %}\
{% for footer in commit.footers %}{% if 'BREAKING CHANGE' in footer.token %}
{% raw %} {% endraw %}- {{ footer.value }}\
{% endif %}{% endfor %}\
{% endif%}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat_ffi"
version = "1.111.0"
version = "1.132.1"
description = "Deltachat FFI"
edition = "2018"
readme = "README.md"
@@ -23,8 +23,9 @@ serde_json = "1.0"
tokio = { version = "1", features = ["rt-multi-thread"] }
anyhow = "1"
thiserror = "1"
rand = "0.7"
once_cell = "1.17.0"
rand = "0.8"
once_cell = "1.18.0"
yerpc = { version = "0.5.1", features = ["anyhow_expose"] }
[features]
default = ["vendored"]

View File

@@ -846,7 +846,7 @@ EXCLUDE_PATTERNS =
# exclude all test directories use the pattern */test/*
######################################################
EXCLUDE_SYMBOLS = dc_aheader_t dc_apeerstate_t dc_e2ee_helper_t dc_imap_t dc_job*_t dc_key_t dc_keyring_t dc_loginparam_t dc_mime*_t
EXCLUDE_SYMBOLS = dc_aheader_t dc_apeerstate_t dc_e2ee_helper_t dc_imap_t dc_job*_t dc_key_t dc_loginparam_t dc_mime*_t
EXCLUDE_SYMBOLS += dc_saxparser_t dc_simplify_t dc_smtp_t dc_sqlite3_t dc_strbuilder_t dc_param_t dc_hash_t dc_hashelem_t
EXCLUDE_SYMBOLS += _dc_* jsmn*
######################################################

View File

@@ -72,7 +72,6 @@ typedef struct _dc_event_emitter dc_accounts_event_emitter_t;
*
* The example above uses "pthreads",
* however, you can also use anything else for thread handling.
* All deltachat-core functions, unless stated otherwise, are thread-safe.
*
* Now you can **configure the context:**
*
@@ -142,6 +141,72 @@ typedef struct _dc_event_emitter dc_accounts_event_emitter_t;
* ~~~
*
*
* ## Thread safety
*
* All deltachat-core functions, unless stated otherwise, are thread-safe.
* In particular, it is safe to pass the same dc_context_t pointer
* to multiple functions running concurrently in different threads.
*
* All the functions are guaranteed not to use the reference passed to them
* after returning. If the function spawns a long-running process,
* such as dc_configure() or dc_imex(), it will ensure that the objects
* passed to them are not deallocated as long as they are needed.
* For example, it is safe to call dc_imex(context, ...) and
* call dc_context_unref(context) immediately after return from dc_imex().
* It is however **not safe** to call dc_context_unref(context) concurrently
* until dc_imex() returns, because dc_imex() may have not increased
* the reference count of dc_context_t yet.
*
* This means that the context may be still in use after
* dc_context_unref() call.
* For example, it is possible to start the import/export process,
* call dc_context_unref(context) immediately after
* and observe #DC_EVENT_IMEX_PROGRESS events via the event emitter.
* Once dc_get_next_event() returns NULL,
* it is safe to terminate the application.
*
* It is recommended to create dc_context_t in the main thread
* and only call dc_context_unref() once other threads that may use it,
* such as the event loop thread, are terminated.
* Common mistake is to use dc_context_unref() as a way
* to cause dc_get_next_event() return NULL and terminate event loop this way.
* If event loop thread is inside a function taking dc_context_t
* as an argument at the moment dc_context_unref() is called on the main thread,
* the behavior is undefined.
*
* Recommended way to safely terminate event loop
* and shutdown the application is
* to use a boolean variable
* indicating that the event loop should stop
* and check it in the event loop thread
* every time before calling dc_get_next_event().
* To terminate the event loop, main thread should:
* 1. Notify background threads,
* such as event loop (blocking in dc_get_next_event())
* and message processing loop (blocking in dc_wait_next_msgs()),
* that they should terminate by atomically setting the
* boolean flag in the memory
* shared between the main thread and background loop threads.
* 2. Call dc_stop_io() or dc_accounts_stop_io(), depending
* on whether a single account or account manager is used.
* Stopping I/O is guaranteed to emit at least one event
* and interrupt the event loop even if it was blocked on dc_get_next_event().
* Stopping I/O is guaranteed to interrupt a single dc_wait_next_msgs().
* 3. Wait until the event loop thread notices the flag,
* exits the event loop and terminates.
* 4. Call dc_context_unref() or dc_accounts_unref().
* 5. Keep calling dc_get_next_event() in a loop until it returns NULL,
* indicating that the contexts are deallocated.
* 6. Terminate the application.
*
* When using C API via FFI in runtimes that use automatic memory management,
* such as CPython, JVM or Node.js, take care to ensure the correct
* shutdown order and avoid calling dc_context_unref() or dc_accounts_unref()
* on the objects still in use in other threads,
* e.g. by keeping a reference to the wrapper object.
* The details depend on the runtime being used.
*
*
* ## Class reference
*
* For a class reference, see the "Classes" link atop.
@@ -235,6 +300,19 @@ dc_context_t* dc_context_new_closed (const char* dbfile);
int dc_context_open (dc_context_t *context, const char* passphrase);
/**
* Changes the passphrase on the open database.
* Existing database must already be encrypted and the passphrase cannot be NULL or empty.
* It is impossible to encrypt unencrypted database with this method and vice versa.
*
* @memberof dc_context_t
* @param context The context object.
* @param passphrase The new passphrase.
* @return 1 on success, 0 on error.
*/
int dc_context_change_passphrase (dc_context_t* context, const char* passphrase);
/**
* Returns 1 if database is open.
*
@@ -305,7 +383,12 @@ char* dc_get_blobdir (const dc_context_t* context);
/**
* Configure the context. The configuration is handled by key=value pairs as:
*
* - `addr` = address to display (always needed)
* - `addr` = Email address to use for configuration.
* If dc_configure() fails this is not the email address actually in use.
* Use `configured_addr` to find out the email address actually in use.
* - `configured_addr` = Email address actually in use.
* Unless for testing, do not set this value using dc_set_config().
* Instead, set `addr` and call dc_configure().
* - `mail_server` = IMAP-server, guessed if left out
* - `mail_user` = IMAP-username, guessed if left out
* - `mail_pw` = IMAP-password (always needed)
@@ -354,17 +437,19 @@ char* dc_get_blobdir (const dc_context_t* context);
* 0=watch all folders normally (default)
* changes require restarting IO by calling dc_stop_io() and then dc_start_io().
* - `show_emails` = DC_SHOW_EMAILS_OFF (0)=
* show direct replies to chats only (default),
* show direct replies to chats only,
* DC_SHOW_EMAILS_ACCEPTED_CONTACTS (1)=
* also show all mails of confirmed contacts,
* DC_SHOW_EMAILS_ALL (2)=
* also show mails of unconfirmed contacts.
* also show mails of unconfirmed contacts (default).
* - `key_gen_type` = DC_KEY_GEN_DEFAULT (0)=
* generate recommended key type (default),
* DC_KEY_GEN_RSA2048 (1)=
* generate RSA 2048 keypair
* DC_KEY_GEN_ED25519 (2)=
* generate Ed25519 keypair
* generate Curve25519 keypair
* DC_KEY_GEN_RSA4096 (3)=
* generate RSA 4096 keypair
* - `save_mime_headers` = 1=save mime headers
* and make dc_get_mime_headers() work for subsequent calls,
* 0=do not save mime headers (default)
@@ -395,11 +480,25 @@ char* dc_get_blobdir (const dc_context_t* context);
* If no type is prefixed, the videochat is handled completely in a browser.
* - `bot` = Set to "1" if this is a bot.
* Prevents adding the "Device messages" and "Saved messages" chats,
* adds Auto-Submitted header to outgoing messages
* and accepts contact requests automatically (calling dc_accept_chat() is not needed for bots).
* adds Auto-Submitted header to outgoing messages,
* accepts contact requests automatically (calling dc_accept_chat() is not needed for bots)
* and does not cut large incoming text messages.
* - `last_msg_id` = database ID of the last message processed by the bot.
* This ID and IDs below it are guaranteed not to be returned
* by dc_get_next_msgs() and dc_wait_next_msgs().
* The value is updated automatically
* when dc_markseen_msgs() is called,
* but the bot can also set it manually if it processed
* the message but does not want to mark it as seen.
* For most bots calling `dc_markseen_msgs()` is the
* recommended way to update this value
* even for self-sent messages.
* - `fetch_existing_msgs` = 1=fetch most recent existing messages on configure (default),
* 0=do not fetch existing messages on configure.
* In both cases, existing recipients are added to the contact database.
* - `disable_idle` = 1=disable IMAP IDLE even if the server supports it,
* 0=use IMAP IDLE if the server supports it.
* This is a developer option used for testing polling used as an IDLE fallback.
* - `download_limit` = Messages up to this number of bytes are downloaded automatically.
* For larger messages, only the header is downloaded and a placeholder is shown.
* These messages can be downloaded fully using dc_download_full_msg() later.
@@ -408,6 +507,16 @@ char* dc_get_blobdir (const dc_context_t* context);
* to not mess up with non-delivery-reports or read-receipts.
* 0=no limit (default).
* Changes affect future messages only.
* - `gossip_period` = How often to gossip Autocrypt keys in chats with multiple recipients, in
* seconds. 2 days by default.
* This is not supposed to be changed by UIs and only used for testing.
* - `verified_one_on_one_chats` = Feature flag for verified 1:1 chats; the UI should set it
* to 1 if it supports verified 1:1 chats.
* Regardless of this setting, `dc_chat_is_protected()` returns true while the key is verified,
* and when the key changes, an info message is posted into the chat.
* 0=Nothing else happens when the key changes.
* 1=After the key changed, `dc_chat_can_send()` returns false and `dc_chat_is_protection_broken()` returns true
* until `dc_accept_chat()` is called.
* - `ui.*` = All keys prefixed by `ui.` can be used by the user-interfaces for system-specific purposes.
* The prefix should be followed by the system and maybe subsystem,
* e.g. `ui.desktop.foo`, `ui.desktop.linux.bar`, `ui.android.foo`, `ui.dc40.bar`, `ui.bot.simplebot.baz`.
@@ -732,7 +841,7 @@ void dc_maybe_network (dc_context_t* context);
* @param context The context as created by dc_context_new().
* @param addr The e-mail address of the user. This must match the
* configured_addr setting of the context as well as the UID of the key.
* @param public_data ASCII armored public key.
* @param public_data Ignored, actual public key is extracted from secret_data.
* @param secret_data ASCII armored secret key.
* @return 1 on success, 0 on failure.
*/
@@ -786,7 +895,8 @@ int dc_preconfigure_keypair (dc_context_t* context, const cha
* - if the flag DC_GCL_ADD_ALLDONE_HINT is set, DC_CHAT_ID_ALLDONE_HINT
* is added as needed.
* @param query_str An optional query for filtering the list. Only chats matching this query
* are returned. Give NULL for no filtering.
* are returned. Give NULL for no filtering. When `is:unread` is contained in the query,
* the chatlist is filtered such that only chats with unread messages show up.
* @param query_id An optional contact ID for filtering the list. Only chats including this contact ID
* are returned. Give 0 for no filtering.
* @return A chatlist as an dc_chatlist_t object.
@@ -1001,6 +1111,7 @@ uint32_t dc_send_videochat_invitation (dc_context_t* context, uint32_t chat_id);
* received overrides all previously received reactions. It is
* possible to remove all reactions by sending an empty string.
*
* @deprecated 2023-11-27, use jsonrpc method `send_reaction` instead
* @memberof dc_context_t
* @param context The context object.
* @param msg_id ID of the message you react to.
@@ -1013,6 +1124,7 @@ uint32_t dc_send_reaction (dc_context_t* context, uint32_t msg_id, char *reactio
/**
* Get a structure with reactions to the message.
*
* @deprecated 2023-11-27, use jsonrpc method `get_message_reactions` instead
* @memberof dc_context_t
* @param context The context object.
* @param msg_id The message ID to get reactions for.
@@ -1026,7 +1138,7 @@ dc_reactions_t* dc_get_msg_reactions (dc_context_t *context, int msg_id);
*
* In JS land, that would be mapped to something as:
* ```
* success = window.webxdc.sendUpdate('{"action":"move","src":"A3","dest":"B4"}', 'move A3 B4');
* success = window.webxdc.sendUpdate('{payload: {"action":"move","src":"A3","dest":"B4"}}', 'move A3 B4');
* ```
* `context` and `msg_id` are not needed in JS as those are unique within a webxdc instance.
* See dc_get_webxdc_status_updates() for the receiving counterpart.
@@ -1244,6 +1356,20 @@ int dc_get_msg_cnt (dc_context_t* context, uint32_t ch
int dc_get_fresh_msg_cnt (dc_context_t* context, uint32_t chat_id);
/**
* Returns a list of similar chats.
*
* @warning This is an experimental API which may change or be removed in the future.
*
* @memberof dc_context_t
* @param context The context object as returned from dc_context_new().
* @param chat_id The ID of the chat for which to find similar chats.
* @return The list of similar chats.
* On errors, NULL is returned.
* Must be freed using dc_chatlist_unref() when no longer used.
*/
dc_chatlist_t* dc_get_similar_chatlist (dc_context_t* context, uint32_t chat_id);
/**
* Estimate the number of messages that will be deleted
@@ -1283,6 +1409,56 @@ int dc_estimate_deletion_cnt (dc_context_t* context, int from_ser
dc_array_t* dc_get_fresh_msgs (dc_context_t* context);
/**
* Returns the message IDs of all messages of any chat
* with a database ID higher than `last_msg_id` config value.
*
* This function is intended for use by bots.
* Self-sent messages, device messages,
* messages from contact requests
* and muted chats are included,
* but messages from explicitly blocked contacts
* and chats are ignored.
*
* This function may be called as a part of event loop
* triggered by DC_EVENT_INCOMING_MSG if you are only interested
* in the incoming messages.
* Otherwise use a separate message processing loop
* calling dc_wait_next_msgs() in a separate thread.
*
* @memberof dc_context_t
* @param context The context object as returned from dc_context_new().
* @return An array of message IDs, must be dc_array_unref()'d when no longer used.
* On errors, the list is empty. NULL is never returned.
*/
dc_array_t* dc_get_next_msgs (dc_context_t* context);
/**
* Waits for notification of new messages
* and returns an array of new message IDs.
* See the documentation for dc_get_next_msgs()
* for the details of return value.
*
* This function waits for internal notification of
* a new message in the database and returns afterwards.
* Notification is also sent when I/O is started
* to allow processing new messages
* and when I/O is stopped using dc_stop_io() or dc_accounts_stop_io()
* to allow for manual interruption of the message processing loop.
* The function may return an empty array if there are
* no messages after notification,
* which may happen on start or if the message is quickly deleted
* after adding it to the database.
*
* @memberof dc_context_t
* @param context The context object as returned from dc_context_new().
* @return An array of message IDs, must be dc_array_unref()'d when no longer used.
* On errors, the list is empty. NULL is never returned.
*/
dc_array_t* dc_wait_next_msgs (dc_context_t* context);
/**
* Mark all messages in a chat as _noticed_.
* _Noticed_ messages are no longer _fresh_ and do not count as being unseen
@@ -1325,6 +1501,7 @@ dc_array_t* dc_get_chat_media (dc_context_t* context, uint32_t ch
* Typically used to implement the "next" and "previous" buttons
* in a gallery or in a media player.
*
* @deprecated Deprecated 2023-10-03, use dc_get_chat_media() and navigate the returned array instead.
* @memberof dc_context_t
* @param context The context object as returned from dc_context_new().
* @param msg_id The ID of the current message from which the next or previous message should be searched.
@@ -1343,24 +1520,6 @@ dc_array_t* dc_get_chat_media (dc_context_t* context, uint32_t ch
uint32_t dc_get_next_media (dc_context_t* context, uint32_t msg_id, int dir, int msg_type, int msg_type2, int msg_type3);
/**
* Enable or disable protection against active attacks.
* To enable protection, it is needed that all members are verified;
* if this condition is met, end-to-end-encryption is always enabled
* and only the verified keys are used.
*
* Sends out #DC_EVENT_CHAT_MODIFIED on changes
* and #DC_EVENT_MSGS_CHANGED if a status message was sent.
*
* @memberof dc_context_t
* @param context The context object as returned from dc_context_new().
* @param chat_id The ID of the chat to change the protection for.
* @param protect 1=protect chat, 0=unprotect chat
* @return 1=success, 0=error, e.g. some members may be unverified
*/
int dc_set_chat_protection (dc_context_t* context, uint32_t chat_id, int protect);
/**
* Set chat visibility to pinned, archived or normal.
*
@@ -1554,24 +1713,12 @@ uint32_t dc_create_group_chat (dc_context_t* context, int protect
* Create a new broadcast list.
*
* Broadcast lists are similar to groups on the sending device,
* however, recipients get the messages in normal one-to-one chats
* and will not be aware of other members.
* however, recipients get the messages in a read-only chat
* and will see who the other members are.
*
* Replies to broadcasts go only to the sender
* and not to all broadcast recipients.
* Moreover, replies will not appear in the broadcast list
* but in the one-to-one chat with the person answering.
*
* The name and the image of the broadcast list is set automatically
* and is visible to the sender only.
* Not asking for these data allows more focused creation
* and we bypass the question who will get which data.
* Also, many users will have at most one broadcast list
* so, a generic name and image is sufficient at the first place.
*
* Later on, however, the name can be changed using dc_set_chat_name().
* The image cannot be changed to have a unique, recognizable icon in the chat lists.
* All in all, this is also what other messengers are doing here.
* For historical reasons, this function does not take a name directly,
* instead you have to set the name using dc_set_chat_name()
* after creating the broadcast list.
*
* @memberof dc_context_t
* @param context The context object.
@@ -1882,6 +2029,11 @@ int dc_resend_msgs (dc_context_t* context, const uint3
* Moreover, timer is started for incoming ephemeral messages.
* This also happens for contact requests chats.
*
* This function updates last_msg_id configuration value
* to the maximum of the current value and IDs passed to this function.
* Bots which mark messages as seen can rely on this side effect
* to avoid updating last_msg_id value manually.
*
* One #DC_EVENT_MSGS_NOTICED event is emitted per modified chat.
*
* @memberof dc_context_t
@@ -2109,8 +2261,7 @@ dc_contact_t* dc_get_contact (dc_context_t* context, uint32_t co
* the backup is not encrypted.
* The backup contains all contacts, chats, images and other data and device independent settings.
* The backup does not contain device dependent settings as ringtones or LED notification settings.
* The name of the backup is typically `delta-chat-<day>.tar`, if more than one backup is create on a day,
* the format is `delta-chat-<day>-<number>.tar`
* The name of the backup is `delta-chat-backup-<day>-<number>-<addr>.tar`.
*
* - **DC_IMEX_IMPORT_BACKUP** (12) - `param1` is the file (not: directory) to import. `param2` is the passphrase.
* The file is normally created by DC_IMEX_EXPORT_BACKUP and detected by dc_imex_has_backup(). Importing a backup
@@ -2123,6 +2274,7 @@ dc_contact_t* dc_get_contact (dc_context_t* context, uint32_t co
*
* - **DC_IMEX_IMPORT_SELF_KEYS** (2) - Import private keys found in the directory given as `param1`.
* The last imported key is made the default keys unless its name contains the string `legacy`. Public keys are not imported.
* If `param1` is a filename, import the private key from the file and make it the default.
*
* While dc_imex() returns immediately, the started job may take a while,
* you can stop it using dc_stop_ongoing_process(). During execution of the job,
@@ -2410,7 +2562,7 @@ dc_lot_t* dc_check_qr (dc_context_t* context, const char*
* the Verified-Group-Invite protocol is offered in the QR code;
* works for protected groups as well as for normal groups.
* If set to 0, the Setup-Contact protocol is offered in the QR code.
* See https://countermitm.readthedocs.io/en/latest/new.html
* See https://securejoin.readthedocs.io/en/latest/new.html
* for details about both protocols.
* @return The text that should go to the QR code,
* On errors, an empty QR code is returned, NULL is never returned.
@@ -2446,7 +2598,7 @@ char* dc_get_securejoin_qr_svg (dc_context_t* context, uint32_
*
* Subsequent calls of dc_join_securejoin() will abort previous, unfinished handshakes.
*
* See https://countermitm.readthedocs.io/en/latest/new.html
* See https://securejoin.readthedocs.io/en/latest/new.html
* for details about both protocols.
*
* @memberof dc_context_t
@@ -2715,6 +2867,12 @@ void dc_backup_provider_wait (dc_backup_provider_t* backup_provider);
/**
* Frees a dc_backup_provider_t object.
*
* If the provider has not yet finished, as indicated by
* dc_backup_provider_wait() or the #DC_EVENT_IMEX_PROGRESS event with value
* of 0 (failed) or 1000 (succeeded), this will also abort any in-progress
* transfer. If this aborts the provider a #DC_EVENT_IMEX_PROGRESS event with
* value 0 (failed) will be emitted.
*
* @memberof dc_backup_provider_t
* @param backup_provider The backup provider object as created by
* dc_backup_provider_new().
@@ -2784,16 +2942,18 @@ int dc_receive_backup (dc_context_t* context, const char* qr);
* use dc_accounts_remove_account().
*
* @memberof dc_accounts_t
* @param os_name
* @param dir The directory to create the context-databases in.
* If the directory does not exist,
* dc_accounts_new() will try to create it.
* @param writable Whether the returned account manager is writable, i.e. calling these functions on
* it is possible: dc_accounts_add_account(), dc_accounts_add_closed_account(),
* dc_accounts_migrate_account(), dc_accounts_remove_account(), dc_accounts_select_account().
* @return An account manager object.
* The object must be passed to the other account manager functions
* and must be freed using dc_accounts_unref() after usage.
* On errors, NULL is returned.
*/
dc_accounts_t* dc_accounts_new (const char* os_name, const char* dir);
dc_accounts_t* dc_accounts_new (const char* dir, int writable);
/**
@@ -3572,9 +3732,22 @@ int dc_chat_can_send (const dc_chat_t* chat);
/**
* Check if a chat is protected.
* Protected chats contain only verified members and encryption is always enabled.
* Protected chats are created using dc_create_group_chat() by setting the 'protect' parameter to 1.
* The status can be changed using dc_set_chat_protection().
*
* End-to-end encryption is guaranteed in protected chats
* and only verified contacts
* as determined by dc_contact_is_verified()
* can be added to protected chats.
*
* Protected chats are created using dc_create_group_chat()
* by setting the 'protect' parameter to 1.
* 1:1 chats become protected or unprotected automatically
* if `verified_one_on_one_chats` setting is enabled.
*
* UI should display a green checkmark
* in the chat title,
* in the chatlist item
* and in the chat profile
* if chat protection is enabled.
*
* @memberof dc_chat_t
* @param chat The chat object.
@@ -3583,6 +3756,26 @@ int dc_chat_can_send (const dc_chat_t* chat);
int dc_chat_is_protected (const dc_chat_t* chat);
/**
* Checks if the chat was protected, and then an incoming message broke this protection.
*
* This function is only useful if the UI enabled the `verified_one_on_one_chats` feature flag,
* otherwise it will return false for all chats.
*
* 1:1 chats are automatically set as protected when a contact is verified.
* When a message comes in that is not encrypted / signed correctly,
* the chat is automatically set as unprotected again.
* dc_chat_is_protection_broken() will return true until dc_accept_chat() is called.
*
* The UI should let the user confirm that this is OK with a message like
* `Bob sent a message from another device. Tap to learn more` and then call dc_accept_chat().
* @memberof dc_chat_t
* @param chat The chat object.
* @return 1=chat protection broken, 0=otherwise.
*/
int dc_chat_is_protection_broken (const dc_chat_t* chat);
/**
* Check if locations are sent to the chat
* at the time the object was created using dc_get_chat().
@@ -3787,7 +3980,7 @@ int64_t dc_msg_get_received_timestamp (const dc_msg_t* msg);
* Get the message time used for sorting.
* This function returns the timestamp that is used for sorting the message
* into lists as returned e.g. by dc_get_chat_msgs().
* This may be the reveived time, the sending time or another time.
* This may be the received time, the sending time or another time.
*
* To get the receiving time, use dc_msg_get_received_timestamp().
* To get the sending time, use dc_msg_get_timestamp().
@@ -3840,16 +4033,17 @@ char* dc_msg_get_text (const dc_msg_t* msg);
*/
char* dc_msg_get_subject (const dc_msg_t* msg);
/**
* Find out full path, file name and extension of the file associated with a
* message.
* Find out full path of the file associated with a message.
*
* Typically files are associated with images, videos, audios, documents.
* Plain text messages do not have a file.
* File name may be mangled. To obtain the original attachment filename use dc_msg_get_filename().
*
* @memberof dc_msg_t
* @param msg The message object.
* @return The full path, the file name, and the extension of the file associated with the message.
* @return The full path (with file name and extension) of the file associated with the message.
* If there is no file associated with the message, an empty string is returned.
* NULL is never returned and the returned value must be released using dc_str_unref().
*/
@@ -3857,14 +4051,13 @@ char* dc_msg_get_file (const dc_msg_t* msg);
/**
* Get a base file name without the path. The base file name includes the extension; the path
* is not returned. To get the full path, use dc_msg_get_file().
* Get an original attachment filename, with extension but without the path. To get the full path,
* use dc_msg_get_file().
*
* @memberof dc_msg_t
* @param msg The message object.
* @return The base file name plus the extension without part. If there is no file
* associated with the message, an empty string is returned. The returned
* value must be released using dc_str_unref().
* @return The attachment filename. If there is no file associated with the message, an empty string
* is returned. The returned value must be released using dc_str_unref().
*/
char* dc_msg_get_filename (const dc_msg_t* msg);
@@ -4177,7 +4370,7 @@ int dc_msg_is_forwarded (const dc_msg_t* msg);
* Check if the message is an informational message, created by the
* device or by another users. Such messages are not "typed" by the user but
* created due to other actions,
* e.g. dc_set_chat_name(), dc_set_chat_profile_image(), dc_set_chat_protection()
* e.g. dc_set_chat_name(), dc_set_chat_profile_image(),
* or dc_add_contact_to_chat().
*
* These messages are typically shown in the center of the chat view,
@@ -4388,15 +4581,18 @@ int dc_msg_has_html (dc_msg_t* msg);
* if they are larger than the limit set by the dc_set_config()-option `download_limit`.
*
* The function returns one of:
* - @ref DC_DOWNLOAD_DONE - The message does not need any further download action
* and should be rendered as usual.
* - @ref DC_DOWNLOAD_AVAILABLE - There is additional content to download.
* In addition to the usual message rendering,
* the UI shall show a download button that calls dc_download_full_msg()
* - @ref DC_DOWNLOAD_IN_PROGRESS - Download was started with dc_download_full_msg() and is still in progress.
* If the download fails or succeeds,
* the event @ref DC_EVENT_MSGS_CHANGED is emitted.
* - @ref DC_DOWNLOAD_FAILURE - Download error, the user may start over calling dc_download_full_msg() again.
* - @ref DC_DOWNLOAD_DONE - The message does not need any further download action
* and should be rendered as usual.
* - @ref DC_DOWNLOAD_AVAILABLE - There is additional content to download.
* In addition to the usual message rendering,
* the UI shall show a download button that calls dc_download_full_msg()
* - @ref DC_DOWNLOAD_IN_PROGRESS - Download was started with dc_download_full_msg() and is still in progress.
* If the download fails or succeeds,
* the event @ref DC_EVENT_MSGS_CHANGED is emitted.
*
* - @ref DC_DOWNLOAD_UNDECIPHERABLE - The message does not need any futher download action.
* It was fully downloaded, but we failed to decrypt it.
* - @ref DC_DOWNLOAD_FAILURE - Download error, the user may start over calling dc_download_full_msg() again.
*
* @memberof dc_msg_t
* @param msg The message object.
@@ -4854,10 +5050,16 @@ int dc_contact_is_blocked (const dc_contact_t* contact);
/**
* Check if a contact was verified. E.g. by a secure-join QR code scan
* and if the key has not changed since this verification.
* Check if the contact
* can be added to verified chats,
* i.e. has a verified key
* and Autocrypt key matches the verified key.
*
* The UI may draw a checkbox or something like that beside verified contacts.
* If contact is verified
* UI should display green checkmark after the contact name
* in contact list items,
* in chat member list items
* and in profiles if no chat with the contact exist (otherwise, use dc_chat_is_protected()).
*
* @memberof dc_contact_t
* @param contact The contact object.
@@ -4867,31 +5069,24 @@ int dc_contact_is_blocked (const dc_contact_t* contact);
int dc_contact_is_verified (dc_contact_t* contact);
/**
* Return the address that verified a contact
* Return the contact ID that verified a contact.
*
* The UI may use this in addition to a checkmark showing the verification status
* If the function returns non-zero result,
* display green checkmark in the profile and "Introduced by ..." line
* with the name and address of the contact
* formatted by dc_contact_get_name_n_addr.
*
* If this function returns a verifier,
* this does not necessarily mean
* you can add the contact to verified chats.
* Use dc_contact_is_verified() to check
* if a contact can be added to a verified chat instead.
*
* @memberof dc_contact_t
* @param contact The contact object.
* @return
* A string containing the verifiers address. If it is the same address as the contact itself,
* we verified the contact ourself. If it is an empty string, we don't have verifier
* information or the contact is not verified.
*/
char* dc_contact_get_verifier_addr (dc_contact_t* contact);
/**
* Return the `ContactId` that verified a contact
*
* The UI may use this in addition to a checkmark showing the verification status
*
* @memberof dc_contact_t
* @param contact The contact object.
* @return
* The `ContactId` of the verifiers address. If it is the same address as the contact itself,
* The contact ID of the verifier. If it is DC_CONTACT_ID_SELF,
* we verified the contact ourself. If it is 0, we don't have verifier information or
* the contact is not verified.
*/
@@ -5090,6 +5285,7 @@ int64_t dc_lot_get_timestamp (const dc_lot_t* lot);
/**
* @class dc_reactions_t
* @deprecated 2023-11-27, use jsonrpc method `get_message_reactions` instead
*
* An object representing all reactions for a single message.
*/
@@ -5097,6 +5293,7 @@ int64_t dc_lot_get_timestamp (const dc_lot_t* lot);
/**
* Returns array of contacts which reacted to the given message.
*
* @deprecated 2023-11-27, use jsonrpc method `get_message_reactions` instead
* @memberof dc_reactions_t
* @param reactions The object containing message reactions.
* @return array of contact IDs. Use dc_array_get_cnt() to get array length and
@@ -5108,6 +5305,7 @@ dc_array_t* dc_reactions_get_contacts(dc_reactions_t* reactions);
/**
* Returns a string containing space-separated reactions of a single contact.
*
* @deprecated 2023-11-27, use jsonrpc method `get_message_reactions` instead
* @memberof dc_reactions_t
* @param reactions The object containing message reactions.
* @param contact_id ID of the contact.
@@ -5123,6 +5321,7 @@ char* dc_reactions_get_by_contact_id(dc_reactions_t* reactions, uint32
*
* Reactions objects are created by dc_get_msg_reactions().
*
* @deprecated 2023-11-27
* @memberof dc_reactions_t
* @param reactions The object to free.
* If NULL is given, nothing is done.
@@ -5468,7 +5667,6 @@ void dc_reactions_unref (dc_reactions_t* reactions);
*/
/**
* @class dc_jsonrpc_instance_t
*
@@ -5517,6 +5715,17 @@ void dc_jsonrpc_request(dc_jsonrpc_instance_t* jsonrpc_instance, const char* req
*/
char* dc_jsonrpc_next_response(dc_jsonrpc_instance_t* jsonrpc_instance);
/**
* Make a JSON-RPC call and return a response.
*
* @memberof dc_jsonrpc_instance_t
* @param jsonrpc_instance jsonrpc instance as returned from dc_jsonrpc_init().
* @param input JSON-RPC request.
* @return JSON-RPC response as string, must be freed using dc_str_unref() after usage.
* If there is no response, NULL is returned.
*/
char* dc_jsonrpc_blocking_call(dc_jsonrpc_instance_t* jsonrpc_instance, const char *input);
/**
* @class dc_event_emitter_t
*
@@ -5705,6 +5914,14 @@ void dc_event_unref(dc_event_t* event);
*/
#define DC_EVENT_IMAP_MESSAGE_MOVED 105
/**
* Emitted before going into IDLE on the Inbox folder.
*
* @param data1 0
* @param data2 0
*/
#define DC_EVENT_IMAP_INBOX_IDLE 106
/**
* Emitted when a new blob file was successfully written
*
@@ -5856,6 +6073,15 @@ void dc_event_unref(dc_event_t* event);
#define DC_EVENT_MSG_READ 2015
/**
* A single message is deleted.
*
* @param data1 (int) chat_id
* @param data2 (int) msg_id
*/
#define DC_EVENT_MSG_DELETED 2016
/**
* Chat changed. The name or the image of a chat group was changed or members were added or removed.
* Or the verify state of a chat has changed.
@@ -5956,6 +6182,7 @@ void dc_event_unref(dc_event_t* event);
* @param data2 (int) The progress as:
* 400=vg-/vc-request-with-auth sent, typically shown as "alice@addr verified, introducing myself."
* (Bob has verified alice and waits until Alice does the same for him)
* 1000=vg-member-added/vc-contact-confirm received
*/
#define DC_EVENT_SECUREJOIN_JOINER_PROGRESS 2061
@@ -6034,6 +6261,7 @@ void dc_event_unref(dc_event_t* event);
#define DC_KEY_GEN_DEFAULT 0
#define DC_KEY_GEN_RSA2048 1
#define DC_KEY_GEN_ED25519 2
#define DC_KEY_GEN_RSA4096 3
/**
@@ -6147,22 +6375,27 @@ void dc_event_unref(dc_event_t* event);
/**
* Download not needed, see dc_msg_get_download_state() for details.
*/
#define DC_DOWNLOAD_DONE 0
#define DC_DOWNLOAD_DONE 0
/**
* Download available, see dc_msg_get_download_state() for details.
*/
#define DC_DOWNLOAD_AVAILABLE 10
#define DC_DOWNLOAD_AVAILABLE 10
/**
* Download failed, see dc_msg_get_download_state() for details.
*/
#define DC_DOWNLOAD_FAILURE 20
#define DC_DOWNLOAD_FAILURE 20
/**
* Download not needed, see dc_msg_get_download_state() for details.
*/
#define DC_DOWNLOAD_UNDECIPHERABLE 30
/**
* Download in progress, see dc_msg_get_download_state() for details.
*/
#define DC_DOWNLOAD_IN_PROGRESS 1000
#define DC_DOWNLOAD_IN_PROGRESS 1000
@@ -6327,7 +6560,7 @@ void dc_event_unref(dc_event_t* event);
/// - %1$s will be replaced by the name of the verified contact
#define DC_STR_CONTACT_VERIFIED 35
/// "Cannot verify %1$s."
/// "Cannot establish guaranteed end-to-end encryption with %1$s."
///
/// Used in status messages.
/// - %1$s will be replaced by the name of the contact that cannot be verified
@@ -6517,15 +6750,6 @@ void dc_event_unref(dc_event_t* event);
/// Used in error strings.
#define DC_STR_ERROR_NO_NETWORK 87
/// "Chat protection enabled."
///
/// @deprecated Deprecated, replaced by DC_STR_MSG_YOU_ENABLED_PROTECTION and DC_STR_MSG_PROTECTION_ENABLED_BY.
#define DC_STR_PROTECTION_ENABLED 88
/// @deprecated Deprecated, replaced by DC_STR_MSG_YOU_DISABLED_PROTECTION and DC_STR_MSG_PROTECTION_DISABLED_BY.
#define DC_STR_PROTECTION_DISABLED 89
/// "Reply"
///
/// Used in summaries.
@@ -6970,25 +7194,30 @@ void dc_event_unref(dc_event_t* event);
/// `%2$s` will be replaced by name and address of the contact.
#define DC_STR_EPHEMERAL_TIMER_WEEKS_BY_OTHER 157
/// "You enabled chat protection."
/// "Scan to set up second device for %1$s"
///
/// Used in status messages.
#define DC_STR_PROTECTION_ENABLED_BY_YOU 158
/// `%1$s` will be replaced by name and address of the account.
#define DC_STR_BACKUP_TRANSFER_QR 162
/// "Chat protection enabled by %1$s."
/// "Account transferred to your second device."
///
/// `%1$s` will be replaced by name and address of the contact.
///
/// Used in status messages.
#define DC_STR_PROTECTION_ENABLED_BY_OTHER 159
/// Used as a device message after a successful backup transfer.
#define DC_STR_BACKUP_TRANSFER_MSG_BODY 163
/// "You disabled chat protection."
#define DC_STR_PROTECTION_DISABLED_BY_YOU 160
/// "Chat protection disabled by %1$s."
/// "Messages are guaranteed to be end-to-end encrypted from now on."
///
/// `%1$s` will be replaced by name and address of the contact.
#define DC_STR_PROTECTION_DISABLED_BY_OTHER 161
/// Used in info messages.
#define DC_STR_CHAT_PROTECTION_ENABLED 170
/// "%1$s sent a message from another device."
///
/// Used in info messages.
#define DC_STR_CHAT_PROTECTION_DISABLED 171
/// "Others will only see this group after you sent a first message."
///
/// Used as the first info messages in newly created groups.
#define DC_STR_NEW_GROUP_SEND_FIRST_MESSAGE 172
/**
* @}

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,4 @@
openrpc/openrpc.json
accounts/
.cargo

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat-jsonrpc"
version = "1.111.0"
version = "1.132.1"
description = "DeltaChat JSON-RPC API"
edition = "2021"
default-run = "deltachat-jsonrpc-server"
@@ -15,25 +15,26 @@ required-features = ["webserver"]
anyhow = "1"
deltachat = { path = ".." }
num-traits = "0.2"
schemars = "0.8.13"
serde = { version = "1.0", features = ["derive"] }
tempfile = "3.3.0"
tempfile = "3.8.0"
log = "0.4"
async-channel = { version = "1.8.0" }
futures = { version = "0.3.26" }
serde_json = "1.0.91"
yerpc = { version = "0.4.3", features = ["anyhow_expose"] }
typescript-type-def = { version = "0.5.5", features = ["json_value"] }
tokio = { version = "1.25.0" }
sanitize-filename = "0.4"
walkdir = "2.3.2"
async-channel = { version = "2.0.0" }
futures = { version = "0.3.28" }
serde_json = "1.0.105"
yerpc = { version = "0.5.2", features = ["anyhow_expose", "openrpc"] }
typescript-type-def = { version = "0.5.8", features = ["json_value"] }
tokio = { version = "1.33.0" }
sanitize-filename = "0.5"
walkdir = "2.3.3"
base64 = "0.21"
# optional dependencies
axum = { version = "0.6.11", optional = true, features = ["ws"] }
axum = { version = "0.7", optional = true, features = ["ws"] }
env_logger = { version = "0.10.0", optional = true }
[dev-dependencies]
tokio = { version = "1.25.0", features = ["full", "rt-multi-thread"] }
tokio = { version = "1.33.0", features = ["full", "rt-multi-thread"] }
[features]

View File

@@ -108,10 +108,10 @@ This will build the `deltachat-jsonrpc-server` binary and then run a test suite
The test suite includes some tests that need online connectivity and a way to create test email accounts. To run these tests, talk to DeltaChat developers to get a token for the `testrun.org` service, or use a local instance of [`mailadm`](https://github.com/deltachat/docker-mailadm).
Then, set the `DCC_NEW_TMP_EMAIL` environment variable to your mailadm token before running the tests.
Then, set the `CHATMAIL_DOMAIN` environment variable to your testing email server domain.
```
DCC_NEW_TMP_EMAIL=https://testrun.org/new_email?t=yourtoken npm run test
CHATMAIL_DOMAIN=chat.example.org npm run test
```
#### Test Coverage

View File

@@ -4,51 +4,50 @@ use std::{collections::HashMap, str::FromStr};
use anyhow::{anyhow, bail, ensure, Context, Result};
pub use deltachat::accounts::Accounts;
use deltachat::qr::Qr;
use deltachat::{
chat::{
self, add_contact_to_chat, forward_msgs, get_chat_media, get_chat_msgs, get_chat_msgs_ex,
marknoticed_chat, remove_contact_from_chat, Chat, ChatId, ChatItem, MessageListOptions,
ProtectionStatus,
},
chatlist::Chatlist,
config::Config,
constants::DC_MSG_ID_DAYMARKER,
contact::{may_be_valid_addr, Contact, ContactId, Origin},
context::get_info,
ephemeral::Timer,
imex, location,
message::{
self, delete_msgs, get_msg_info, markseen_msgs, Message, MessageState, MsgId, Viewtype,
},
provider::get_provider_info,
qr,
qr_code_generator::{generate_backup_qr, get_securejoin_qr_svg},
reaction::send_reaction,
securejoin,
stock_str::StockMessage,
webxdc::StatusUpdateSerial,
use deltachat::chat::{
self, add_contact_to_chat, forward_msgs, get_chat_media, get_chat_msgs, get_chat_msgs_ex,
marknoticed_chat, remove_contact_from_chat, Chat, ChatId, ChatItem, MessageListOptions,
ProtectionStatus,
};
use deltachat::chatlist::Chatlist;
use deltachat::config::Config;
use deltachat::constants::DC_MSG_ID_DAYMARKER;
use deltachat::contact::{may_be_valid_addr, Contact, ContactId, Origin};
use deltachat::context::get_info;
use deltachat::ephemeral::Timer;
use deltachat::imex;
use deltachat::location;
use deltachat::message::get_msg_read_receipts;
use deltachat::message::{
self, delete_msgs, markseen_msgs, Message, MessageState, MsgId, Viewtype,
};
use deltachat::provider::get_provider_info;
use deltachat::qr::{self, Qr};
use deltachat::qr_code_generator::{generate_backup_qr, get_securejoin_qr_svg};
use deltachat::reaction::{get_msg_reactions, send_reaction};
use deltachat::securejoin;
use deltachat::stock_str::StockMessage;
use deltachat::webxdc::StatusUpdateSerial;
use sanitize_filename::is_sanitized;
use tokio::fs;
use tokio::sync::{watch, Mutex, RwLock};
use walkdir::WalkDir;
use yerpc::rpc;
pub mod events;
pub mod types;
use num_traits::FromPrimitive;
use types::account::Account;
use types::chat::FullChat;
use types::chat_list::ChatListEntry;
use types::contact::ContactObject;
use types::message::MessageData;
use types::message::MessageObject;
use types::events::Event;
use types::http::HttpResponse;
use types::message::{MessageData, MessageObject, MessageReadReceipt};
use types::provider_info::ProviderInfo;
use types::reactions::JSONRPCReactions;
use types::webxdc::WebxdcMessageInfo;
use self::types::message::MessageLoadResult;
use self::types::message::{MessageInfo, MessageLoadResult};
use self::types::{
chat::{BasicChat, JSONRPCChatVisibility, MuteDuration},
location::JsonrpcLocation,
@@ -154,16 +153,26 @@ impl CommandApi {
// Misc top level functions
// ---------------------------------------------
/// Check if an email address is valid.
/// Checks if an email address is valid.
async fn check_email_validity(&self, email: String) -> bool {
may_be_valid_addr(&email)
}
/// Get general system info.
/// Returns general system info.
async fn get_system_info(&self) -> BTreeMap<&'static str, String> {
get_info()
}
/// Get the next event.
async fn get_next_event(&self) -> Result<Event> {
let event_emitter = self.accounts.read().await.get_event_emitter();
event_emitter
.recv()
.await
.map(|event| event.into())
.context("event channel is closed")
}
// ---------------------------------------------
// Account Management
// ---------------------------------------------
@@ -205,20 +214,20 @@ impl CommandApi {
let context_option = self.accounts.read().await.get_account(id);
if let Some(ctx) = context_option {
accounts.push(Account::from_context(&ctx, id).await?)
} else {
println!("account with id {id} doesn't exist anymore");
}
}
Ok(accounts)
}
/// Starts background tasks for all accounts.
async fn start_io_for_all_accounts(&self) -> Result<()> {
self.accounts.read().await.start_io().await;
self.accounts.write().await.start_io().await;
Ok(())
}
/// Stops background tasks for all accounts.
async fn stop_io_for_all_accounts(&self) -> Result<()> {
self.accounts.read().await.stop_io().await;
self.accounts.write().await.stop_io().await;
Ok(())
}
@@ -226,14 +235,16 @@ impl CommandApi {
// Methods that work on individual accounts
// ---------------------------------------------
async fn start_io(&self, id: u32) -> Result<()> {
let ctx = self.get_context(id).await?;
/// Starts background tasks for a single account.
async fn start_io(&self, account_id: u32) -> Result<()> {
let mut ctx = self.get_context(account_id).await?;
ctx.start_io().await;
Ok(())
}
async fn stop_io(&self, id: u32) -> Result<()> {
let ctx = self.get_context(id).await?;
/// Stops background tasks for a single account.
async fn stop_io(&self, account_id: u32) -> Result<()> {
let ctx = self.get_context(account_id).await?;
ctx.stop_io().await;
Ok(())
}
@@ -300,11 +311,13 @@ impl CommandApi {
ctx.get_info().await
}
/// Sets the given configuration key.
async fn set_config(&self, account_id: u32, key: String, value: Option<String>) -> Result<()> {
let ctx = self.get_context(account_id).await?;
set_config(&ctx, &key, value.as_deref()).await
}
/// Updates a batch of configuration values.
async fn batch_set_config(
&self,
account_id: u32,
@@ -336,6 +349,7 @@ impl CommandApi {
Ok(qr_object)
}
/// Returns configuration value for the given key.
async fn get_config(&self, account_id: u32, key: String) -> Result<Option<String>> {
let ctx = self.get_context(account_id).await?;
get_config(&ctx, &key).await
@@ -369,7 +383,7 @@ impl CommandApi {
/// Configures this account with the currently set parameters.
/// Setup the credential config before calling this.
async fn configure(&self, account_id: u32) -> Result<()> {
let ctx = self.get_context(account_id).await?;
let mut ctx = self.get_context(account_id).await?;
ctx.stop_io().await;
let result = ctx.configure().await;
if result.is_err() {
@@ -453,6 +467,49 @@ impl CommandApi {
ChatId::new(chat_id).get_fresh_msg_cnt(&ctx).await
}
/// Gets messages to be processed by the bot and returns their IDs.
///
/// Only messages with database ID higher than `last_msg_id` config value
/// are returned. After processing the messages, the bot should
/// update `last_msg_id` by calling [`markseen_msgs`]
/// or manually updating the value to avoid getting already
/// processed messages.
///
/// [`markseen_msgs`]: Self::markseen_msgs
async fn get_next_msgs(&self, account_id: u32) -> Result<Vec<u32>> {
let ctx = self.get_context(account_id).await?;
let msg_ids = ctx
.get_next_msgs()
.await?
.iter()
.map(|msg_id| msg_id.to_u32())
.collect();
Ok(msg_ids)
}
/// Waits for messages to be processed by the bot and returns their IDs.
///
/// This function is similar to [`get_next_msgs`],
/// but waits for internal new message notification before returning.
/// New message notification is sent when new message is added to the database,
/// on initialization, when I/O is started and when I/O is stopped.
/// This allows bots to use `wait_next_msgs` in a loop to process
/// old messages after initialization and during the bot runtime.
/// To shutdown the bot, stopping I/O can be used to interrupt
/// pending or next `wait_next_msgs` call.
///
/// [`get_next_msgs`]: Self::get_next_msgs
async fn wait_next_msgs(&self, account_id: u32) -> Result<Vec<u32>> {
let ctx = self.get_context(account_id).await?;
let msg_ids = ctx
.wait_next_msgs()
.await?
.iter()
.map(|msg_id| msg_id.to_u32())
.collect();
Ok(msg_ids)
}
/// Estimate the number of messages that will be deleted
/// by the set_config()-options `delete_device_after` or `delete_server_after`.
/// This is typically used to show the estimated impact to the user
@@ -496,7 +553,7 @@ impl CommandApi {
list_flags: Option<u32>,
query_string: Option<String>,
query_contact_id: Option<u32>,
) -> Result<Vec<ChatListEntry>> {
) -> Result<Vec<u32>> {
let ctx = self.get_context(account_id).await?;
let list = Chatlist::try_load(
&ctx,
@@ -505,32 +562,43 @@ impl CommandApi {
query_contact_id.map(ContactId::new),
)
.await?;
let mut l: Vec<ChatListEntry> = Vec::with_capacity(list.len());
let mut l: Vec<u32> = Vec::with_capacity(list.len());
for i in 0..list.len() {
l.push(ChatListEntry(
list.get_chat_id(i)?.to_u32(),
list.get_msg_id(i)?.unwrap_or_default().to_u32(),
));
l.push(list.get_chat_id(i)?.to_u32());
}
Ok(l)
}
/// Returns chats similar to the given one.
///
/// Experimental API, subject to change without notice.
async fn get_similar_chat_ids(&self, account_id: u32, chat_id: u32) -> Result<Vec<u32>> {
let ctx = self.get_context(account_id).await?;
let chat_id = ChatId::new(chat_id);
let list = chat_id
.get_similar_chat_ids(&ctx)
.await?
.into_iter()
.map(|(chat_id, _metric)| chat_id.to_u32())
.collect();
Ok(list)
}
async fn get_chatlist_items_by_entries(
&self,
account_id: u32,
entries: Vec<ChatListEntry>,
entries: Vec<u32>,
) -> Result<HashMap<u32, ChatListItemFetchResult>> {
// todo custom json deserializer for ChatListEntry?
let ctx = self.get_context(account_id).await?;
let mut result: HashMap<u32, ChatListItemFetchResult> =
HashMap::with_capacity(entries.len());
for entry in entries.iter() {
for &entry in entries.iter() {
result.insert(
entry.0,
entry,
match get_chat_list_item_by_id(&ctx, entry).await {
Ok(res) => res,
Err(err) => ChatListItemFetchResult::Error {
id: entry.0,
id: entry,
error: format!("{err:#}"),
},
},
@@ -610,7 +678,7 @@ impl CommandApi {
/// the Verified-Group-Invite protocol is offered in the QR code;
/// works for protected groups as well as for normal groups.
/// If not set, the Setup-Contact protocol is offered in the QR code.
/// See https://countermitm.readthedocs.io/en/latest/new.html
/// See https://securejoin.readthedocs.io/en/latest/new.html
/// for details about both protocols.
///
/// return format: `[code, svg]`
@@ -639,7 +707,7 @@ impl CommandApi {
///
/// Subsequent calls of `secure_join()` will abort previous, unfinished handshakes.
///
/// See https://countermitm.readthedocs.io/en/latest/new.html
/// See https://securejoin.readthedocs.io/en/latest/new.html
/// for details about both protocols.
///
/// **qr**: The text of the scanned QR code. Typically, the same string as given
@@ -747,24 +815,12 @@ impl CommandApi {
/// Create a new broadcast list.
///
/// Broadcast lists are similar to groups on the sending device,
/// however, recipients get the messages in normal one-to-one chats
/// and will not be aware of other members.
/// however, recipients get the messages in a read-only chat
/// and will see who the other members are.
///
/// Replies to broadcasts go only to the sender
/// and not to all broadcast recipients.
/// Moreover, replies will not appear in the broadcast list
/// but in the one-to-one chat with the person answering.
///
/// The name and the image of the broadcast list is set automatically
/// and is visible to the sender only.
/// Not asking for these data allows more focused creation
/// and we bypass the question who will get which data.
/// Also, many users will have at most one broadcast list
/// so, a generic name and image is sufficient at the first place.
///
/// Later on, however, the name can be changed using dc_set_chat_name().
/// The image cannot be changed to have a unique, recognizable icon in the chat lists.
/// All in all, this is also what other messengers are doing here.
/// For historical reasons, this function does not take a name directly,
/// instead you have to set the name using dc_set_chat_name()
/// after creating the broadcast list.
async fn create_broadcast_list(&self, account_id: u32) -> Result<u32> {
let ctx = self.get_context(account_id).await?;
chat::create_broadcast_list(&ctx)
@@ -849,7 +905,7 @@ impl CommandApi {
) -> Result<u32> {
let ctx = self.get_context(account_id).await?;
let mut msg = Message::new(Viewtype::Text);
msg.set_text(Some(text));
msg.set_text(text);
let message_id =
deltachat::chat::add_device_msg(&ctx, Some(&label), Some(&mut msg)).await?;
Ok(message_id.to_u32())
@@ -944,6 +1000,11 @@ impl CommandApi {
/// Moreover, timer is started for incoming ephemeral messages.
/// This also happens for contact requests chats.
///
/// This function updates `last_msg_id` configuration value
/// to the maximum of the current value and IDs passed to this function.
/// Bots which mark messages as seen can rely on this side effect
/// to avoid updating `last_msg_id` value manually.
///
/// One #DC_EVENT_MSGS_NOTICED event is emitted per modified chat.
async fn markseen_msgs(&self, account_id: u32, msg_ids: Vec<u32>) -> Result<()> {
let ctx = self.get_context(account_id).await?;
@@ -1062,7 +1123,35 @@ impl CommandApi {
/// max. text returned by dc_msg_get_text() (about 30000 characters).
async fn get_message_info(&self, account_id: u32, message_id: u32) -> Result<String> {
let ctx = self.get_context(account_id).await?;
get_msg_info(&ctx, MsgId::new(message_id)).await
MsgId::new(message_id).get_info(&ctx).await
}
/// Returns additional information for single message.
async fn get_message_info_object(
&self,
account_id: u32,
message_id: u32,
) -> Result<MessageInfo> {
let ctx = self.get_context(account_id).await?;
MessageInfo::from_msg_id(&ctx, MsgId::new(message_id)).await
}
/// Returns contacts that sent read receipts and the time of reading.
async fn get_message_read_receipts(
&self,
account_id: u32,
message_id: u32,
) -> Result<Vec<MessageReadReceipt>> {
let ctx = self.get_context(account_id).await?;
let receipts = get_msg_read_receipts(&ctx, MsgId::new(message_id))
.await?
.iter()
.map(|(contact_id, ts)| MessageReadReceipt {
contact_id: contact_id.to_u32(),
timestamp: *ts,
})
.collect();
Ok(receipts)
}
/// Asks the core to start downloading a message fully.
@@ -1082,17 +1171,17 @@ impl CommandApi {
}
/// Search messages containing the given query string.
/// Searching can be done globally (chat_id=0) or in a specified chat only (chat_id set).
/// Searching can be done globally (chat_id=None) or in a specified chat only (chat_id set).
///
/// Global chat results are typically displayed using dc_msg_get_summary(), chat
/// search results may just hilite the corresponding messages and present a
/// Global search results are typically displayed using dc_msg_get_summary(), chat
/// search results may just highlight the corresponding messages and present a
/// prev/next button.
///
/// For global search, result is limited to 1000 messages,
/// this allows incremental search done fast.
/// So, when getting exactly 1000 results, the result may be truncated;
/// the UIs may display sth. as "1000+ messages found" in this case.
/// Chat search (if a chat_id is set) is not limited.
/// For the global search, the result is limited to 1000 messages,
/// this allows an incremental search done fast.
/// So, when getting exactly 1000 messages, the result actually may be truncated;
/// the UIs may display sth. like "1000+ messages found" in this case.
/// The chat search (if chat_id is set) is not limited.
async fn search_messages(
&self,
account_id: u32,
@@ -1265,7 +1354,7 @@ impl CommandApi {
) -> Result<()> {
let ctx = self.get_context(account_id).await?;
let contact_id = ContactId::new(contact_id);
let contact = Contact::load_from_db(&ctx, contact_id).await?;
let contact = Contact::get_by_id(&ctx, contact_id).await?;
let addr = contact.get_addr();
Contact::create(&ctx, &name, addr).await?;
Ok(())
@@ -1302,6 +1391,19 @@ impl CommandApi {
// chat
// ---------------------------------------------
/// Returns the [`ChatId`] for the 1:1 chat with `contact_id` if it exists.
///
/// If it does not exist, `None` is returned.
async fn get_chat_id_by_contact_id(
&self,
account_id: u32,
contact_id: u32,
) -> Result<Option<u32>> {
let ctx = self.get_context(account_id).await?;
let chat_id = ChatId::lookup_by_contact(&ctx, ContactId::new(contact_id)).await?;
Ok(chat_id.map(|id| id.to_u32()))
}
/// Returns all message IDs of the given types in a chat.
/// Typically used to show a gallery.
///
@@ -1339,6 +1441,10 @@ impl CommandApi {
///
/// one combined call for getting chat::get_next_media for both directions
/// the manual chat::get_next_media in only one direction is not exposed by the jsonrpc yet
///
/// Deprecated 2023-10-03, use `get_chat_media` method
/// and navigate the returned array instead.
#[allow(deprecated)]
async fn get_neighboring_chat_media(
&self,
account_id: u32,
@@ -1610,6 +1716,15 @@ impl CommandApi {
Ok(general_purpose::STANDARD_NO_PAD.encode(blob))
}
/// Makes an HTTP GET request and returns a response.
///
/// `url` is the HTTP or HTTPS URL.
async fn get_http_response(&self, account_id: u32, url: String) -> Result<HttpResponse> {
let ctx = self.get_context(account_id).await?;
let response = deltachat::net::read_url_blob(&ctx, &url).await?.into();
Ok(response)
}
/// Forward messages to another chat.
///
/// All types of messages can be forwarded,
@@ -1627,6 +1742,20 @@ impl CommandApi {
forward_msgs(&ctx, &message_ids, ChatId::new(chat_id)).await
}
/// Resend messages and make information available for newly added chat members.
/// Resending sends out the original message, however, recipients and webxdc-status may differ.
/// Clients that already have the original message can still ignore the resent message as
/// they have tracked the state by dedicated updates.
///
/// Some messages cannot be resent, eg. info-messages, drafts, already pending messages or messages that are not sent by SELF.
///
/// message_ids all message IDs that should be resend. All messages must belong to the same chat.
async fn resend_messages(&self, account_id: u32, message_ids: Vec<u32>) -> Result<()> {
let ctx = self.get_context(account_id).await?;
let message_ids: Vec<MsgId> = message_ids.into_iter().map(MsgId::new).collect();
chat::resend_msgs(&ctx, &message_ids).await
}
async fn send_sticker(
&self,
account_id: u32,
@@ -1638,6 +1767,9 @@ impl CommandApi {
let mut msg = Message::new(Viewtype::Sticker);
msg.set_file(&sticker_path, None);
// JSON-rpc does not need heuristics to turn [Viewtype::Sticker] into [Viewtype::Image]
msg.force_sticker();
let message_id = deltachat::chat::send_msg(&ctx, ChatId::new(chat_id), &mut msg).await?;
Ok(message_id.to_u32())
}
@@ -1659,6 +1791,21 @@ impl CommandApi {
Ok(message_id.to_u32())
}
/// Returns reactions to the message.
async fn get_message_reactions(
&self,
account_id: u32,
message_id: u32,
) -> Result<Option<JSONRPCReactions>> {
let ctx = self.get_context(account_id).await?;
let reactions = get_msg_reactions(&ctx, MsgId::new(message_id)).await?;
if reactions.is_empty() {
Ok(None)
} else {
Ok(Some(reactions.into()))
}
}
async fn send_msg(&self, account_id: u32, chat_id: u32, data: MessageData) -> Result<u32> {
let ctx = self.get_context(account_id).await?;
let mut message = Message::new(if let Some(viewtype) = data.viewtype {
@@ -1668,9 +1815,7 @@ impl CommandApi {
} else {
Viewtype::Text
});
if data.text.is_some() {
message.set_text(data.text);
}
message.set_text(data.text.unwrap_or_default());
if data.html.is_some() {
message.set_html(data.html);
}
@@ -1701,6 +1846,15 @@ impl CommandApi {
Ok(msg_id)
}
/// Checks if messages can be sent to a given chat.
async fn can_send(&self, account_id: u32, chat_id: u32) -> Result<bool> {
let ctx = self.get_context(account_id).await?;
let chat_id = ChatId::new(chat_id);
let chat = Chat::load_from_db(&ctx, chat_id).await?;
let can_send = chat.can_send(&ctx).await?;
Ok(can_send)
}
// ---------------------------------------------
// functions for the composer
// the composer is the message input field
@@ -1749,7 +1903,7 @@ impl CommandApi {
.context("path conversion to string failed")
}
/// save a sticker to a collection/folder in the account's sticker folder
/// Saves a sticker to a collection/folder in the account's sticker folder.
async fn misc_save_sticker(
&self,
account_id: u32,
@@ -1842,7 +1996,7 @@ impl CommandApi {
let ctx = self.get_context(account_id).await?;
let mut msg = Message::new(Viewtype::Text);
msg.set_text(Some(text));
msg.set_text(text);
let message_id = deltachat::chat::send_msg(&ctx, ChatId::new(chat_id), &mut msg).await?;
Ok(message_id.to_u32())
@@ -1865,9 +2019,7 @@ impl CommandApi {
} else {
Viewtype::Text
});
if text.is_some() {
message.set_text(text);
}
message.set_text(text.unwrap_or_default());
if let Some(file) = file {
message.set_file(file, None);
}
@@ -1904,16 +2056,20 @@ impl CommandApi {
text: Option<String>,
file: Option<String>,
quoted_message_id: Option<u32>,
view_type: Option<MessageViewtype>,
) -> Result<()> {
let ctx = self.get_context(account_id).await?;
let mut draft = Message::new(if file.is_some() {
Viewtype::File
} else {
Viewtype::Text
});
if text.is_some() {
draft.set_text(text);
}
let mut draft = Message::new(view_type.map_or_else(
|| {
if file.is_some() {
Viewtype::File
} else {
Viewtype::Text
}
},
|v| v.into(),
));
draft.set_text(text.unwrap_or_default());
if let Some(file) = file {
draft.set_file(file, None);
}
@@ -1932,6 +2088,23 @@ impl CommandApi {
ChatId::new(chat_id).set_draft(&ctx, Some(&mut draft)).await
}
// send the chat's current set draft
async fn misc_send_draft(&self, account_id: u32, chat_id: u32) -> Result<u32> {
let ctx = self.get_context(account_id).await?;
if let Some(draft) = ChatId::new(chat_id).get_draft(&ctx).await? {
let mut draft = draft;
let msg_id = chat::send_msg(&ctx, ChatId::new(chat_id), &mut draft)
.await?
.to_u32();
Ok(msg_id)
} else {
Err(anyhow!(
"chat with id {} doesn't have draft message",
chat_id
))
}
}
}
// Helper functions (to prevent code duplication)

View File

@@ -6,8 +6,8 @@ use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;
#[derive(Serialize, TypeDef)]
#[serde(tag = "type")]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum Account {
#[serde(rename_all = "camelCase")]
Configured {

View File

@@ -1,6 +1,6 @@
use std::time::{Duration, SystemTime};
use anyhow::{anyhow, bail, Result};
use anyhow::{bail, Context as _, Result};
use deltachat::chat::{self, get_chat_contacts, ChatVisibility};
use deltachat::chat::{Chat, ChatId};
use deltachat::constants::Chattype;
@@ -13,11 +13,22 @@ use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;
use super::contact::ContactObject;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct FullChat {
id: u32,
name: String,
/// True if the chat is protected.
///
/// UI should display a green checkmark
/// in the chat title,
/// in the chat profile title and
/// in the chatlist item
/// if chat protection is enabled.
/// UI should also display a green checkmark
/// in the contact profile
/// if 1:1 chat with this contact exists and is protected.
is_protected: bool,
profile_image: Option<String>, //BLOBS ?
archived: bool,
@@ -31,6 +42,7 @@ pub struct FullChat {
fresh_message_counter: usize,
// is_group - please check over chat.type in frontend instead
is_contact_request: bool,
is_protection_broken: bool,
is_device_chat: bool,
self_in_group: bool,
is_muted: bool,
@@ -53,7 +65,9 @@ impl FullChat {
contacts.push(
ContactObject::try_from_dc_contact(
context,
Contact::load_from_db(context, *contact_id).await?,
Contact::get_by_id(context, *contact_id)
.await
.context("failed to load contact")?,
)
.await?,
)
@@ -72,8 +86,9 @@ impl FullChat {
let was_seen_recently = if chat.get_type() == Chattype::Single {
match contact_ids.get(0) {
Some(contact) => Contact::load_from_db(context, *contact)
.await?
Some(contact) => Contact::get_by_id(context, *contact)
.await
.context("failed to load contact for was_seen_recently")?
.was_seen_recently(),
None => false,
}
@@ -89,10 +104,7 @@ impl FullChat {
is_protected: chat.is_protected(),
profile_image, //BLOBS ?
archived: chat.get_visibility() == chat::ChatVisibility::Archived,
chat_type: chat
.get_type()
.to_u32()
.ok_or_else(|| anyhow!("unknown chat type id"))?, // TODO get rid of this unwrap?
chat_type: chat.get_type().to_u32().context("unknown chat type id")?,
is_unpromoted: chat.is_unpromoted(),
is_self_talk: chat.is_self_talk(),
contacts,
@@ -100,6 +112,7 @@ impl FullChat {
color,
fresh_message_counter,
is_contact_request: chat.is_contact_request(),
is_protection_broken: chat.is_protection_broken(),
is_device_chat: chat.is_device_talk(),
self_in_group: contact_ids.contains(&ContactId::SELF),
is_muted: chat.is_muted(),
@@ -121,11 +134,22 @@ impl FullChat {
/// - can_send
///
/// used when you only need the basic metadata of a chat like type, name, profile picture
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BasicChat {
id: u32,
name: String,
/// True if the chat is protected.
///
/// UI should display a green checkmark
/// in the chat title,
/// in the chat profile title and
/// in the chatlist item
/// if chat protection is enabled.
/// UI should also display a green checkmark
/// in the contact profile
/// if 1:1 chat with this contact exists and is protected.
is_protected: bool,
profile_image: Option<String>, //BLOBS ?
archived: bool,
@@ -134,6 +158,7 @@ pub struct BasicChat {
is_self_talk: bool,
color: String,
is_contact_request: bool,
is_protection_broken: bool,
is_device_chat: bool,
is_muted: bool,
}
@@ -155,25 +180,24 @@ impl BasicChat {
is_protected: chat.is_protected(),
profile_image, //BLOBS ?
archived: chat.get_visibility() == chat::ChatVisibility::Archived,
chat_type: chat
.get_type()
.to_u32()
.ok_or_else(|| anyhow!("unknown chat type id"))?, // TODO get rid of this unwrap?
chat_type: chat.get_type().to_u32().context("unknown chat type id")?,
is_unpromoted: chat.is_unpromoted(),
is_self_talk: chat.is_self_talk(),
color,
is_contact_request: chat.is_contact_request(),
is_protection_broken: chat.is_protection_broken(),
is_device_chat: chat.is_device_talk(),
is_muted: chat.is_muted(),
})
}
}
#[derive(Clone, Serialize, Deserialize, TypeDef)]
#[derive(Clone, Serialize, Deserialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum MuteDuration {
NotMuted,
Forever,
Until(i64),
Until { duration: i64 },
}
impl MuteDuration {
@@ -181,20 +205,20 @@ impl MuteDuration {
match self {
MuteDuration::NotMuted => Ok(chat::MuteDuration::NotMuted),
MuteDuration::Forever => Ok(chat::MuteDuration::Forever),
MuteDuration::Until(n) => {
if n <= 0 {
MuteDuration::Until { duration } => {
if duration <= 0 {
bail!("failed to read mute duration")
}
Ok(SystemTime::now()
.checked_add(Duration::from_secs(n as u64))
.checked_add(Duration::from_secs(duration as u64))
.map_or(chat::MuteDuration::Forever, chat::MuteDuration::Until))
}
}
}
}
#[derive(Clone, Serialize, Deserialize, TypeDef)]
#[derive(Clone, Serialize, Deserialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "ChatVisibility")]
pub enum JSONRPCChatVisibility {
Normal,

View File

@@ -1,25 +1,21 @@
use anyhow::Result;
use anyhow::{Context, Result};
use deltachat::chat::{Chat, ChatId};
use deltachat::chatlist::get_last_message_for_chat;
use deltachat::constants::*;
use deltachat::contact::{Contact, ContactId};
use deltachat::{
chat::{get_chat_contacts, ChatVisibility},
chatlist::Chatlist,
};
use deltachat::{
chat::{Chat, ChatId},
message::MsgId,
};
use num_traits::cast::ToPrimitive;
use serde::{Deserialize, Serialize};
use serde::Serialize;
use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;
use super::message::MessageViewtype;
#[derive(Deserialize, Serialize, TypeDef)]
pub struct ChatListEntry(pub u32, pub u32);
#[derive(Serialize, TypeDef)]
#[serde(tag = "type")]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum ChatListItemFetchResult {
#[serde(rename_all = "camelCase")]
ChatListItem {
@@ -31,6 +27,8 @@ pub enum ChatListItemFetchResult {
summary_text1: String,
summary_text2: String,
summary_status: u32,
/// showing preview if last chat message is image
summary_preview_image: Option<String>,
is_protected: bool,
is_group: bool,
fresh_message_counter: usize,
@@ -47,6 +45,8 @@ pub enum ChatListItemFetchResult {
/// contact id if this is a dm chat (for view profile entry in context menu)
dm_chat_contact: Option<u32>,
was_seen_recently: bool,
last_message_type: Option<MessageViewtype>,
last_message_id: Option<u32>,
},
#[serde(rename_all = "camelCase")]
ArchiveLink { fresh_message_counter: usize },
@@ -56,14 +56,9 @@ pub enum ChatListItemFetchResult {
pub(crate) async fn get_chat_list_item_by_id(
ctx: &deltachat::context::Context,
entry: &ChatListEntry,
entry: u32,
) -> Result<ChatListItemFetchResult> {
let chat_id = ChatId::new(entry.0);
let last_msgid = match entry.1 {
0 => None,
_ => Some(MsgId::new(entry.1)),
};
let chat_id = ChatId::new(entry);
let fresh_message_counter = chat_id.get_fresh_msg_cnt(ctx).await?;
if chat_id.is_archived_link() {
@@ -72,12 +67,18 @@ pub(crate) async fn get_chat_list_item_by_id(
});
}
let chat = Chat::load_from_db(ctx, chat_id).await?;
let summary = Chatlist::get_summary2(ctx, chat_id, last_msgid, Some(&chat)).await?;
let last_msgid = get_last_message_for_chat(ctx, chat_id).await?;
let chat = Chat::load_from_db(ctx, chat_id).await.context("chat")?;
let summary = Chatlist::get_summary2(ctx, chat_id, last_msgid, Some(&chat))
.await
.context("summary")?;
let summary_text1 = summary.prefix.map_or_else(String::new, |s| s.to_string());
let summary_text2 = summary.text.to_owned();
let summary_preview_image = summary.thumbnail_path;
let visibility = chat.get_visibility();
let avatar_path = chat
@@ -85,12 +86,15 @@ pub(crate) async fn get_chat_list_item_by_id(
.await?
.map(|path| path.to_str().unwrap_or("invalid/path").to_owned());
let last_updated = match last_msgid {
let (last_updated, message_type) = match last_msgid {
Some(id) => {
let last_message = deltachat::message::Message::load_from_db(ctx, id).await?;
Some(last_message.get_timestamp() * 1000)
(
Some(last_message.get_timestamp() * 1000),
Some(last_message.get_viewtype().into()),
)
}
None => None,
None => (None, None),
};
let chat_contacts = get_chat_contacts(ctx, chat_id).await?;
@@ -100,8 +104,9 @@ pub(crate) async fn get_chat_list_item_by_id(
let (dm_chat_contact, was_seen_recently) = if chat.get_type() == Chattype::Single {
let contact = chat_contacts.get(0);
let was_seen_recently = match contact {
Some(contact) => Contact::load_from_db(ctx, *contact)
.await?
Some(contact) => Contact::get_by_id(ctx, *contact)
.await
.context("contact")?
.was_seen_recently(),
None => false,
};
@@ -124,6 +129,7 @@ pub(crate) async fn get_chat_list_item_by_id(
summary_text1,
summary_text2,
summary_status: summary.state.to_u32().expect("impossible"), // idea and a function to transform the constant to strings? or return string enum
summary_preview_image,
is_protected: chat.is_protected(),
is_group: chat.get_type() == Chattype::Group,
fresh_message_counter,
@@ -138,5 +144,7 @@ pub(crate) async fn get_chat_list_item_by_id(
is_broadcast: chat.get_type() == Chattype::Broadcast,
dm_chat_contact,
was_seen_recently,
last_message_type: message_type,
last_message_id: last_msgid.map(|id| id.to_u32()),
})
}

View File

@@ -1,12 +1,11 @@
use anyhow::Result;
use deltachat::contact::VerifiedStatus;
use deltachat::context::Context;
use serde::Serialize;
use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Contact", rename_all = "camelCase")]
pub struct ContactObject {
address: String,
@@ -19,11 +18,30 @@ pub struct ContactObject {
profile_image: Option<String>, // BLOBS
name_and_addr: String,
is_blocked: bool,
/// True if the contact can be added to verified groups.
///
/// If this is true
/// UI should display green checkmark after the contact name
/// in contact list items,
/// in chat member list items
/// and in profiles if no chat with the contact exist.
is_verified: bool,
/// the address that verified this contact
verifier_addr: Option<String>,
/// the id of the contact that verified this contact
/// True if the contact profile title should have a green checkmark.
///
/// This indicates whether 1:1 chat has a green checkmark
/// or will have a green checkmark if created.
is_profile_verified: bool,
/// The ID of the contact that verified this contact.
///
/// If this is present,
/// display a green checkmark and "Introduced by ..."
/// string followed by the verifier contact name and address
/// in the contact profile.
verifier_id: Option<u32>,
/// the contact's last seen timestamp
last_seen: i64,
was_seen_recently: bool,
@@ -38,19 +56,13 @@ impl ContactObject {
Some(path_buf) => path_buf.to_str().map(|s| s.to_owned()),
None => None,
};
let is_verified = contact.is_verified(context).await? == VerifiedStatus::BidirectVerified;
let is_verified = contact.is_verified(context).await?;
let is_profile_verified = contact.is_profile_verified(context).await?;
let (verifier_addr, verifier_id) = if is_verified {
(
contact.get_verifier_addr(context).await?,
contact
.get_verifier_id(context)
.await?
.map(|contact_id| contact_id.to_u32()),
)
} else {
(None, None)
};
let verifier_id = contact
.get_verifier_id(context)
.await?
.map(|contact_id| contact_id.to_u32());
Ok(ContactObject {
address: contact.get_addr().to_owned(),
@@ -64,7 +76,7 @@ impl ContactObject {
name_and_addr: contact.get_name_n_addr(),
is_blocked: contact.is_blocked(),
is_verified,
verifier_addr,
is_profile_verified,
verifier_id,
last_seen: contact.last_seen(),
was_seen_recently: contact.was_seen_recently(),

View File

@@ -1,19 +1,29 @@
use deltachat::{Event, EventType};
use deltachat::{Event as CoreEvent, EventType as CoreEventType};
use serde::Serialize;
use serde_json::{json, Value};
use typescript_type_def::TypeDef;
pub fn event_to_json_rpc_notification(event: Event) -> Value {
let id: JSONRPCEventType = event.typ.into();
json!({
"event": id,
"contextId": event.id,
})
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Event {
/// Event payload.
event: EventType,
/// Account ID.
context_id: u32,
}
#[derive(Serialize, TypeDef)]
#[serde(tag = "type", rename = "Event")]
pub enum JSONRPCEventType {
impl From<CoreEvent> for Event {
fn from(event: CoreEvent) -> Self {
Event {
event: event.typ.into(),
context_id: event.id,
}
}
}
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum EventType {
/// The library-user may write an informational string to the log.
///
/// This event should *not* be reported to the end-user using a popup or something like
@@ -47,6 +57,9 @@ pub enum JSONRPCEventType {
msg: String,
},
/// Emitted before going into IDLE on the Inbox folder.
ImapInboxIdle,
/// Emitted when an new file in the $BLOBDIR was created
NewBlobFile {
file: String,
@@ -161,6 +174,13 @@ pub enum JSONRPCEventType {
msg_id: u32,
},
/// A single message is deleted.
#[serde(rename_all = "camelCase")]
MsgDeleted {
chat_id: u32,
msg_id: u32,
},
/// Chat changed. The name or the image of a chat group was changed or members were added or removed.
/// Or the verify state of a chat has changed.
/// See setChatName(), setChatProfileImage(), addContactToChat()
@@ -283,26 +303,27 @@ pub enum JSONRPCEventType {
},
}
impl From<EventType> for JSONRPCEventType {
fn from(event: EventType) -> Self {
use JSONRPCEventType::*;
impl From<CoreEventType> for EventType {
fn from(event: CoreEventType) -> Self {
use EventType::*;
match event {
EventType::Info(msg) => Info { msg },
EventType::SmtpConnected(msg) => SmtpConnected { msg },
EventType::ImapConnected(msg) => ImapConnected { msg },
EventType::SmtpMessageSent(msg) => SmtpMessageSent { msg },
EventType::ImapMessageDeleted(msg) => ImapMessageDeleted { msg },
EventType::ImapMessageMoved(msg) => ImapMessageMoved { msg },
EventType::NewBlobFile(file) => NewBlobFile { file },
EventType::DeletedBlobFile(file) => DeletedBlobFile { file },
EventType::Warning(msg) => Warning { msg },
EventType::Error(msg) => Error { msg },
EventType::ErrorSelfNotInGroup(msg) => ErrorSelfNotInGroup { msg },
EventType::MsgsChanged { chat_id, msg_id } => MsgsChanged {
CoreEventType::Info(msg) => Info { msg },
CoreEventType::SmtpConnected(msg) => SmtpConnected { msg },
CoreEventType::ImapConnected(msg) => ImapConnected { msg },
CoreEventType::SmtpMessageSent(msg) => SmtpMessageSent { msg },
CoreEventType::ImapMessageDeleted(msg) => ImapMessageDeleted { msg },
CoreEventType::ImapMessageMoved(msg) => ImapMessageMoved { msg },
CoreEventType::ImapInboxIdle => ImapInboxIdle,
CoreEventType::NewBlobFile(file) => NewBlobFile { file },
CoreEventType::DeletedBlobFile(file) => DeletedBlobFile { file },
CoreEventType::Warning(msg) => Warning { msg },
CoreEventType::Error(msg) => Error { msg },
CoreEventType::ErrorSelfNotInGroup(msg) => ErrorSelfNotInGroup { msg },
CoreEventType::MsgsChanged { chat_id, msg_id } => MsgsChanged {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
EventType::ReactionsChanged {
CoreEventType::ReactionsChanged {
chat_id,
msg_id,
contact_id,
@@ -311,92 +332,80 @@ impl From<EventType> for JSONRPCEventType {
msg_id: msg_id.to_u32(),
contact_id: contact_id.to_u32(),
},
EventType::IncomingMsg { chat_id, msg_id } => IncomingMsg {
CoreEventType::IncomingMsg { chat_id, msg_id } => IncomingMsg {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
EventType::IncomingMsgBunch { msg_ids } => IncomingMsgBunch {
CoreEventType::IncomingMsgBunch { msg_ids } => IncomingMsgBunch {
msg_ids: msg_ids.into_iter().map(|id| id.to_u32()).collect(),
},
EventType::MsgsNoticed(chat_id) => MsgsNoticed {
CoreEventType::MsgsNoticed(chat_id) => MsgsNoticed {
chat_id: chat_id.to_u32(),
},
EventType::MsgDelivered { chat_id, msg_id } => MsgDelivered {
CoreEventType::MsgDelivered { chat_id, msg_id } => MsgDelivered {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
EventType::MsgFailed { chat_id, msg_id } => MsgFailed {
CoreEventType::MsgFailed { chat_id, msg_id } => MsgFailed {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
EventType::MsgRead { chat_id, msg_id } => MsgRead {
CoreEventType::MsgRead { chat_id, msg_id } => MsgRead {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
EventType::ChatModified(chat_id) => ChatModified {
CoreEventType::MsgDeleted { chat_id, msg_id } => MsgDeleted {
chat_id: chat_id.to_u32(),
msg_id: msg_id.to_u32(),
},
CoreEventType::ChatModified(chat_id) => ChatModified {
chat_id: chat_id.to_u32(),
},
EventType::ChatEphemeralTimerModified { chat_id, timer } => {
CoreEventType::ChatEphemeralTimerModified { chat_id, timer } => {
ChatEphemeralTimerModified {
chat_id: chat_id.to_u32(),
timer: timer.to_u32(),
}
}
EventType::ContactsChanged(contact) => ContactsChanged {
CoreEventType::ContactsChanged(contact) => ContactsChanged {
contact_id: contact.map(|c| c.to_u32()),
},
EventType::LocationChanged(contact) => LocationChanged {
CoreEventType::LocationChanged(contact) => LocationChanged {
contact_id: contact.map(|c| c.to_u32()),
},
EventType::ConfigureProgress { progress, comment } => {
CoreEventType::ConfigureProgress { progress, comment } => {
ConfigureProgress { progress, comment }
}
EventType::ImexProgress(progress) => ImexProgress { progress },
EventType::ImexFileWritten(path) => ImexFileWritten {
CoreEventType::ImexProgress(progress) => ImexProgress { progress },
CoreEventType::ImexFileWritten(path) => ImexFileWritten {
path: path.to_str().unwrap_or_default().to_owned(),
},
EventType::SecurejoinInviterProgress {
CoreEventType::SecurejoinInviterProgress {
contact_id,
progress,
} => SecurejoinInviterProgress {
contact_id: contact_id.to_u32(),
progress,
},
EventType::SecurejoinJoinerProgress {
CoreEventType::SecurejoinJoinerProgress {
contact_id,
progress,
} => SecurejoinJoinerProgress {
contact_id: contact_id.to_u32(),
progress,
},
EventType::ConnectivityChanged => ConnectivityChanged,
EventType::SelfavatarChanged => SelfavatarChanged,
EventType::WebxdcStatusUpdate {
CoreEventType::ConnectivityChanged => ConnectivityChanged,
CoreEventType::SelfavatarChanged => SelfavatarChanged,
CoreEventType::WebxdcStatusUpdate {
msg_id,
status_update_serial,
} => WebxdcStatusUpdate {
msg_id: msg_id.to_u32(),
status_update_serial: status_update_serial.to_u32(),
},
EventType::WebxdcInstanceDeleted { msg_id } => WebxdcInstanceDeleted {
CoreEventType::WebxdcInstanceDeleted { msg_id } => WebxdcInstanceDeleted {
msg_id: msg_id.to_u32(),
},
}
}
}
#[cfg(test)]
#[test]
fn generate_events_ts_types_definition() {
let events = {
let mut buf = Vec::new();
let options = typescript_type_def::DefinitionFileOptions {
root_namespace: None,
..typescript_type_def::DefinitionFileOptions::default()
};
typescript_type_def::write_definition_file::<_, JSONRPCEventType>(&mut buf, options)
.unwrap();
String::from_utf8(buf).unwrap()
};
std::fs::write("typescript/generated/events.ts", events).unwrap();
}

View File

@@ -0,0 +1,29 @@
use deltachat::net::HttpResponse as CoreHttpResponse;
use serde::Serialize;
use typescript_type_def::TypeDef;
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
pub struct HttpResponse {
/// base64-encoded response body.
blob: String,
/// MIME type, e.g. "text/plain" or "text/html".
mimetype: Option<String>,
/// Encoding, e.g. "utf-8".
encoding: Option<String>,
}
impl From<CoreHttpResponse> for HttpResponse {
fn from(response: CoreHttpResponse) -> Self {
use base64::{engine::general_purpose, Engine as _};
let blob = general_purpose::STANDARD_NO_PAD.encode(response.blob);
let mimetype = response.mimetype;
let encoding = response.encoding;
HttpResponse {
blob,
mimetype,
encoding,
}
}
}

View File

@@ -2,7 +2,7 @@ use deltachat::location::Location;
use serde::Serialize;
use typescript_type_def::TypeDef;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Location", rename_all = "camelCase")]
pub struct JsonrpcLocation {
pub location_id: u32,

View File

@@ -1,7 +1,7 @@
use anyhow::{anyhow, Result};
use anyhow::{Context as _, Result};
use deltachat::chat::Chat;
use deltachat::chat::ChatItem;
use deltachat::constants::Chattype;
use deltachat::chat::ChatVisibility;
use deltachat::contact::Contact;
use deltachat::context::Context;
use deltachat::download;
@@ -10,8 +10,7 @@ use deltachat::message::MsgId;
use deltachat::message::Viewtype;
use deltachat::reaction::get_msg_reactions;
use num_traits::cast::ToPrimitive;
use serde::Deserialize;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;
@@ -19,14 +18,14 @@ use super::contact::ContactObject;
use super::reactions::JSONRPCReactions;
use super::webxdc::WebxdcMessageInfo;
#[derive(Serialize, TypeDef)]
#[serde(rename_all = "camelCase", tag = "variant")]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum MessageLoadResult {
Message(MessageObject),
LoadingError { error: String },
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Message", rename_all = "camelCase")]
pub struct MessageObject {
id: u32,
@@ -35,7 +34,7 @@ pub struct MessageObject {
quote: Option<MessageQuote>,
parent_id: Option<u32>,
text: Option<String>,
text: String,
has_location: bool,
has_html: bool,
view_type: MessageViewtype,
@@ -86,7 +85,7 @@ pub struct MessageObject {
reactions: Option<JSONRPCReactions>,
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
enum MessageQuote {
JustText {
@@ -114,8 +113,12 @@ impl MessageObject {
pub async fn from_msg_id(context: &Context, msg_id: MsgId) -> Result<Self> {
let message = Message::load_from_db(context, msg_id).await?;
let sender_contact = Contact::load_from_db(context, message.get_from_id()).await?;
let sender = ContactObject::try_from_dc_contact(context, sender_contact).await?;
let sender_contact = Contact::get_by_id(context, message.get_from_id())
.await
.context("failed to load sender contact")?;
let sender = ContactObject::try_from_dc_contact(context, sender_contact)
.await
.context("failed to load sender contact object")?;
let file_bytes = message.get_filebytes(context).await?.unwrap_or_default();
let override_sender_name = message.get_override_sender_name();
@@ -132,7 +135,9 @@ impl MessageObject {
let quote = if let Some(quoted_text) = message.quoted_text() {
match message.quoted_message(context).await? {
Some(quote) => {
let quote_author = Contact::load_from_db(context, quote.get_from_id()).await?;
let quote_author = Contact::get_by_id(context, quote.get_from_id())
.await
.context("failed to load quote author contact")?;
Some(MessageQuote::WithMessage {
text: quoted_text,
message_id: quote.get_id().to_u32(),
@@ -160,7 +165,9 @@ impl MessageObject {
None
};
let reactions = get_msg_reactions(context, msg_id).await?;
let reactions = get_msg_reactions(context, msg_id)
.await
.context("failed to load message reactions")?;
let reactions = if reactions.is_empty() {
None
} else {
@@ -180,7 +187,7 @@ impl MessageObject {
state: message
.get_state()
.to_u32()
.ok_or_else(|| anyhow!("state conversion to number failed"))?,
.context("state conversion to number failed")?,
error: message.error(),
timestamp: message.get_timestamp(),
@@ -203,7 +210,7 @@ impl MessageObject {
videochat_type: match message.get_videochat_type() {
Some(vct) => Some(
vct.to_u32()
.ok_or_else(|| anyhow!("state conversion to number failed"))?,
.context("videochat type conversion to number failed")?,
),
None => None,
},
@@ -230,7 +237,7 @@ impl MessageObject {
}
}
#[derive(Serialize, Deserialize, TypeDef)]
#[derive(Serialize, Deserialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Viewtype")]
pub enum MessageViewtype {
Unknown,
@@ -306,11 +313,12 @@ impl From<MessageViewtype> for Viewtype {
}
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
pub enum DownloadState {
Done,
Available,
Failure,
Undecipherable,
InProgress,
}
@@ -320,12 +328,13 @@ impl From<download::DownloadState> for DownloadState {
download::DownloadState::Done => DownloadState::Done,
download::DownloadState::Available => DownloadState::Available,
download::DownloadState::Failure => DownloadState::Failure,
download::DownloadState::Undecipherable => DownloadState::Undecipherable,
download::DownloadState::InProgress => DownloadState::InProgress,
}
}
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
pub enum SystemMessageType {
Unknown,
GroupNameChanged,
@@ -380,7 +389,7 @@ impl From<deltachat::mimeparser::SystemMessage> for SystemMessageType {
}
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MessageNotificationInfo {
id: u32,
@@ -438,14 +447,22 @@ impl MessageNotificationInfo {
}
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MessageSearchResult {
id: u32,
author_profile_image: Option<String>,
/// if sender name if overridden it will show it as ~alias
author_name: String,
author_color: String,
chat_name: Option<String>,
author_id: u32,
chat_profile_image: Option<String>,
chat_color: String,
chat_name: String,
chat_type: u32,
is_chat_protected: bool,
is_chat_contact_request: bool,
is_chat_archived: bool,
message: String,
timestamp: i64,
}
@@ -454,30 +471,44 @@ impl MessageSearchResult {
pub async fn from_msg_id(context: &Context, msg_id: MsgId) -> Result<Self> {
let message = Message::load_from_db(context, msg_id).await?;
let chat = Chat::load_from_db(context, message.get_chat_id()).await?;
let sender = Contact::load_from_db(context, message.get_from_id()).await?;
let sender = Contact::get_by_id(context, message.get_from_id()).await?;
let profile_image = match sender.get_profile_image(context).await? {
Some(path_buf) => path_buf.to_str().map(|s| s.to_owned()),
None => None,
};
let chat_profile_image = match chat.get_profile_image(context).await? {
Some(path_buf) => path_buf.to_str().map(|s| s.to_owned()),
None => None,
};
let author_name = if let Some(name) = message.get_override_sender_name() {
format!("~{name}")
} else {
sender.get_display_name().to_owned()
};
let chat_color = color_int_to_hex_string(chat.get_color(context).await?);
Ok(Self {
id: msg_id.to_u32(),
author_profile_image: profile_image,
author_name: sender.get_display_name().to_owned(),
author_name,
author_color: color_int_to_hex_string(sender.get_color()),
chat_name: if chat.get_type() == Chattype::Single {
Some(chat.get_name().to_owned())
} else {
None
},
message: message.get_text().unwrap_or_default(),
author_id: sender.id.to_u32(),
chat_name: chat.get_name().to_owned(),
chat_color,
chat_type: chat.get_type().to_u32().context("unknown chat type id")?,
chat_profile_image,
is_chat_protected: chat.is_protected(),
is_chat_contact_request: chat.is_contact_request(),
is_chat_archived: chat.get_visibility() == ChatVisibility::Archived,
message: message.get_text(),
timestamp: message.get_timestamp(),
})
}
}
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", rename = "MessageListItem", tag = "kind")]
pub enum JSONRPCMessageListItem {
Message {
@@ -503,7 +534,7 @@ impl From<ChatItem> for JSONRPCMessageListItem {
}
}
#[derive(Deserialize, TypeDef)]
#[derive(Deserialize, Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MessageData {
pub text: Option<String>,
@@ -514,3 +545,78 @@ pub struct MessageData {
pub override_sender_name: Option<String>,
pub quoted_message_id: Option<u32>,
}
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MessageReadReceipt {
pub contact_id: u32,
pub timestamp: i64,
}
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct MessageInfo {
rawtext: String,
ephemeral_timer: EphemeralTimer,
/// When message is ephemeral this contains the timestamp of the message expiry
ephemeral_timestamp: Option<i64>,
error: Option<String>,
rfc724_mid: String,
server_urls: Vec<String>,
hop_info: Option<String>,
}
impl MessageInfo {
pub async fn from_msg_id(context: &Context, msg_id: MsgId) -> Result<Self> {
let message = Message::load_from_db(context, msg_id).await?;
let rawtext = msg_id.rawtext(context).await?;
let ephemeral_timer = message.get_ephemeral_timer().into();
let ephemeral_timestamp = match message.get_ephemeral_timer() {
deltachat::ephemeral::Timer::Disabled => None,
deltachat::ephemeral::Timer::Enabled { .. } => Some(message.get_ephemeral_timestamp()),
};
let server_urls =
MsgId::get_info_server_urls(context, message.rfc724_mid().to_owned()).await?;
let hop_info = msg_id.hop_info(context).await?;
Ok(Self {
rawtext,
ephemeral_timer,
ephemeral_timestamp,
error: message.error(),
rfc724_mid: message.rfc724_mid().to_owned(),
server_urls,
hop_info,
})
}
}
#[derive(
Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize, TypeDef, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase", tag = "variant")]
pub enum EphemeralTimer {
/// Timer is disabled.
Disabled,
/// Timer is enabled.
Enabled {
/// Timer duration in seconds.
///
/// The value cannot be 0.
duration: u32,
},
}
impl From<deltachat::ephemeral::Timer> for EphemeralTimer {
fn from(value: deltachat::ephemeral::Timer) -> Self {
match value {
deltachat::ephemeral::Timer::Disabled => EphemeralTimer::Disabled,
deltachat::ephemeral::Timer::Enabled { duration } => {
EphemeralTimer::Enabled { duration }
}
}
}
}

View File

@@ -2,6 +2,8 @@ pub mod account;
pub mod chat;
pub mod chat_list;
pub mod contact;
pub mod events;
pub mod http;
pub mod location;
pub mod message;
pub mod provider_info;

View File

@@ -3,9 +3,11 @@ use num_traits::cast::ToPrimitive;
use serde::Serialize;
use typescript_type_def::TypeDef;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ProviderInfo {
/// Unique ID, corresponding to provider database filename.
pub id: String,
pub before_login_hint: String,
pub overview_page: String,
pub status: u32, // in reality this is an enum, but for simplicity and because it gets converted into a number anyway, we use an u32 here.
@@ -14,6 +16,7 @@ pub struct ProviderInfo {
impl ProviderInfo {
pub fn from_dc_type(provider: Option<&Provider>) -> Option<Self> {
provider.map(|p| ProviderInfo {
id: p.id.to_owned(),
before_login_hint: p.before_login_hint.to_owned(),
overview_page: p.overview_page.to_owned(),
status: p.status.to_u32().unwrap(),

View File

@@ -2,9 +2,9 @@ use deltachat::qr::Qr;
use serde::Serialize;
use typescript_type_def::TypeDef;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Qr", rename_all = "camelCase")]
#[serde(tag = "type")]
#[serde(tag = "kind")]
pub enum QrObject {
AskVerifyContact {
contact_id: u32,

View File

@@ -1,23 +1,37 @@
use std::collections::BTreeMap;
use deltachat::contact::ContactId;
use deltachat::reaction::Reactions;
use serde::Serialize;
use typescript_type_def::TypeDef;
/// A single reaction emoji.
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Reaction", rename_all = "camelCase")]
pub struct JSONRPCReaction {
/// Emoji.
emoji: String,
/// Emoji frequency.
count: usize,
/// True if we reacted with this emoji.
is_from_self: bool,
}
/// Structure representing all reactions to a particular message.
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Reactions", rename_all = "camelCase")]
pub struct JSONRPCReactions {
/// Map from a contact to it's reaction to message.
reactions_by_contact: BTreeMap<u32, Vec<String>>,
/// Unique reactions and their count
reactions: BTreeMap<String, u32>,
/// Unique reactions and their count, sorted in descending order.
reactions: Vec<JSONRPCReaction>,
}
impl From<Reactions> for JSONRPCReactions {
fn from(reactions: Reactions) -> Self {
let mut reactions_by_contact: BTreeMap<u32, Vec<String>> = BTreeMap::new();
let mut unique_reactions: BTreeMap<String, u32> = BTreeMap::new();
for contact_id in reactions.contacts() {
let reaction = reactions.get(contact_id);
@@ -30,18 +44,29 @@ impl From<Reactions> for JSONRPCReactions {
.map(|emoji| emoji.to_owned())
.collect();
reactions_by_contact.insert(contact_id.to_u32(), emojis.clone());
for emoji in emojis {
if let Some(x) = unique_reactions.get_mut(&emoji) {
*x += 1;
} else {
unique_reactions.insert(emoji, 1);
}
}
}
let self_reactions = reactions_by_contact.get(&ContactId::SELF.to_u32());
let mut reactions_v = Vec::new();
for (emoji, count) in reactions.emoji_sorted_by_frequency() {
let is_from_self = if let Some(self_reactions) = self_reactions {
self_reactions.contains(&emoji)
} else {
false
};
let reaction = JSONRPCReaction {
emoji,
count,
is_from_self,
};
reactions_v.push(reaction)
}
JSONRPCReactions {
reactions_by_contact,
reactions: unique_reactions,
reactions: reactions_v,
}
}
}

View File

@@ -8,7 +8,7 @@ use typescript_type_def::TypeDef;
use super::maybe_empty_string_to_option;
#[derive(Serialize, TypeDef)]
#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "WebxdcMessageInfo", rename_all = "camelCase")]
pub struct WebxdcMessageInfo {
/// The name of the app.

View File

@@ -1,5 +1,4 @@
pub mod api;
pub use api::events;
pub use yerpc;
#[cfg(test)]
@@ -14,10 +13,11 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn basic_json_rpc_functionality() -> anyhow::Result<()> {
let tmp_dir = TempDir::new().unwrap().path().into();
let accounts = Accounts::new(tmp_dir).await?;
let writable = true;
let accounts = Accounts::new(tmp_dir, writable).await?;
let api = CommandApi::new(accounts);
let (sender, mut receiver) = unbounded::<String>();
let (sender, receiver) = unbounded::<String>();
let (client, mut rx) = RpcClient::new();
let session = RpcSession::new(client, api);
@@ -36,17 +36,17 @@ mod tests {
let request = r#"{"jsonrpc":"2.0","method":"add_account","params":[],"id":1}"#;
let response = r#"{"jsonrpc":"2.0","id":1,"result":1}"#;
session.handle_incoming(request).await;
let result = receiver.next().await;
let result = receiver.recv().await?;
println!("{result:?}");
assert_eq!(result, Some(response.to_owned()));
assert_eq!(result, response.to_owned());
}
{
let request = r#"{"jsonrpc":"2.0","method":"get_all_account_ids","params":[],"id":2}"#;
let response = r#"{"jsonrpc":"2.0","id":2,"result":[1]}"#;
session.handle_incoming(request).await;
let result = receiver.next().await;
let result = receiver.recv().await?;
println!("{result:?}");
assert_eq!(result, Some(response.to_owned()));
assert_eq!(result, response.to_owned());
}
Ok(())
@@ -55,10 +55,11 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn test_batch_set_config() -> anyhow::Result<()> {
let tmp_dir = TempDir::new().unwrap().path().into();
let accounts = Accounts::new(tmp_dir).await?;
let writable = true;
let accounts = Accounts::new(tmp_dir, writable).await?;
let api = CommandApi::new(accounts);
let (sender, mut receiver) = unbounded::<String>();
let (sender, receiver) = unbounded::<String>();
let (client, mut rx) = RpcClient::new();
let session = RpcSession::new(client, api);
@@ -77,15 +78,15 @@ mod tests {
let request = r#"{"jsonrpc":"2.0","method":"add_account","params":[],"id":1}"#;
let response = r#"{"jsonrpc":"2.0","id":1,"result":1}"#;
session.handle_incoming(request).await;
let result = receiver.next().await;
assert_eq!(result, Some(response.to_owned()));
let result = receiver.recv().await?;
assert_eq!(result, response.to_owned());
}
{
let request = r#"{"jsonrpc":"2.0","method":"batch_set_config","id":2,"params":[1,{"addr":"","mail_user":"","mail_pw":"","mail_server":"","mail_port":"","mail_security":"","imap_certificate_checks":"","send_user":"","send_pw":"","send_server":"","send_port":"","send_security":"","smtp_certificate_checks":"","socks5_enabled":"0","socks5_host":"","socks5_port":"","socks5_user":"","socks5_password":""}]}"#;
let response = r#"{"jsonrpc":"2.0","id":2,"result":null}"#;
session.handle_incoming(request).await;
let result = receiver.next().await;
assert_eq!(result, Some(response.to_owned()));
let result = receiver.recv().await?;
assert_eq!(result, response.to_owned());
}
Ok(())

View File

@@ -6,7 +6,6 @@ use yerpc::axum::handle_ws_rpc;
use yerpc::{RpcClient, RpcSession};
mod api;
use api::events::event_to_json_rpc_notification;
use api::{Accounts, CommandApi};
const DEFAULT_PORT: u16 = 20808;
@@ -20,7 +19,8 @@ async fn main() -> Result<(), std::io::Error> {
.map(|port| port.parse::<u16>().expect("DC_PORT must be a number"))
.unwrap_or(DEFAULT_PORT);
log::info!("Starting with accounts directory `{path}`.");
let accounts = Accounts::new(PathBuf::from(&path)).await.unwrap();
let writable = true;
let accounts = Accounts::new(PathBuf::from(&path), writable).await.unwrap();
let state = CommandApi::new(accounts);
let app = Router::new()
@@ -28,15 +28,13 @@ async fn main() -> Result<(), std::io::Error> {
.layer(Extension(state.clone()));
tokio::spawn(async move {
state.accounts.read().await.start_io().await;
state.accounts.write().await.start_io().await;
});
let addr = SocketAddr::from(([127, 0, 0, 1], port));
log::info!("JSON-RPC WebSocket server listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
Ok(())
}
@@ -44,12 +42,5 @@ async fn main() -> Result<(), std::io::Error> {
async fn handler(ws: WebSocketUpgrade, Extension(api): Extension<CommandApi>) -> Response {
let (client, out_receiver) = RpcClient::new();
let session = RpcSession::new(client.clone(), api.clone());
tokio::spawn(async move {
let events = api.accounts.read().await.get_event_emitter();
while let Some(event) = events.recv().await {
let event = event_to_json_rpc_notification(event);
client.send_notification("event", Some(event)).await.ok();
}
});
handle_ws_rpc(ws, out_receiver, session).await
}

View File

@@ -35,7 +35,7 @@ async function run() {
const accounts = await client.rpc.getAllAccounts();
console.log("accounts loaded", accounts);
for (const account of accounts) {
if (account.type === "Configured") {
if (account.kind === "Configured") {
write(
$head,
`<a href="#" onclick="selectDeltaAccount(${account.id})">
@@ -57,7 +57,7 @@ async function run() {
clear($main);
const selectedAccount = SELECTED_ACCOUNT;
const info = await client.rpc.getAccountInfo(selectedAccount);
if (info.type !== "Configured") {
if (info.kind !== "Configured") {
return write($main, "Account is not configured");
}
write($main, `<h2>${info.addr!}</h2>`);
@@ -67,7 +67,7 @@ async function run() {
null,
null
);
for (const [chatId, _messageId] of chats) {
for (const chatId of chats) {
const chat = await client.rpc.getFullChatById(selectedAccount, chatId);
write($main, `<h3>${chat.name}</h3>`);
const messageIds = await client.rpc.getMessageIds(
@@ -81,8 +81,7 @@ async function run() {
messageIds
);
for (const [_messageId, message] of Object.entries(messages)) {
if (message.variant === "message")
write($main, `<p>${message.text}</p>`);
if (message.kind === "message") write($main, `<p>${message.text}</p>`);
else write($main, `<p>loading error: ${message.error}</p>`);
}
}
@@ -93,9 +92,9 @@ async function run() {
$side,
`
<p class="message">
[<strong>${event.type}</strong> on account ${accountId}]<br>
[<strong>${event.kind}</strong> on account ${accountId}]<br>
<em>f1:</em> ${JSON.stringify(
Object.assign({}, event, { type: undefined })
Object.assign({}, event, { kind: undefined })
)}
</p>`
);

View File

@@ -9,7 +9,6 @@
"@types/chai": "^4.2.21",
"@types/chai-as-promised": "^7.1.5",
"@types/mocha": "^9.0.0",
"@types/node-fetch": "^2.5.7",
"@types/ws": "^7.2.4",
"c8": "^7.10.0",
"chai": "^4.3.4",
@@ -17,7 +16,6 @@
"esbuild": "^0.17.9",
"http-server": "^14.1.1",
"mocha": "^9.1.1",
"node-fetch": "^2.6.1",
"npm-run-all": "^4.1.5",
"prettier": "^2.6.2",
"typedoc": "^0.23.2",
@@ -55,5 +53,5 @@
},
"type": "module",
"types": "dist/deltachat.d.ts",
"version": "1.111.0"
"version": "1.132.1"
}

View File

@@ -1,34 +1,28 @@
import * as T from "../generated/types.js";
import { EventType } from "../generated/types.js";
import * as RPC from "../generated/jsonrpc.js";
import { RawClient } from "../generated/client.js";
import { Event } from "../generated/events.js";
import { WebsocketTransport, BaseTransport, Request } from "yerpc";
import { TinyEmitter } from "@deltachat/tiny-emitter";
type DCWireEvent<T extends Event> = {
event: T;
contextId: number;
};
// export type Events = Record<
// Event["type"] | "ALL",
// (event: DeltaChatEvent<Event>) => void
// >;
type Events = { ALL: (accountId: number, event: Event) => void } & {
[Property in Event["type"]]: (
type Events = { ALL: (accountId: number, event: EventType) => void } & {
[Property in EventType["kind"]]: (
accountId: number,
event: Extract<Event, { type: Property }>
event: Extract<EventType, { kind: Property }>
) => void;
};
type ContextEvents = { ALL: (event: Event) => void } & {
[Property in Event["type"]]: (
event: Extract<Event, { type: Property }>
type ContextEvents = { ALL: (event: EventType) => void } & {
[Property in EventType["kind"]]: (
event: Extract<EventType, { kind: Property }>
) => void;
};
export type DcEvent = Event;
export type DcEventType<T extends Event["type"]> = Extract<Event, { type: T }>;
export type DcEvent = EventType;
export type DcEventType<T extends EventType["kind"]> = Extract<
EventType,
{ kind: T }
>;
export class BaseDeltaChat<
Transport extends BaseTransport<any>
@@ -36,27 +30,34 @@ export class BaseDeltaChat<
rpc: RawClient;
account?: T.Account;
private contextEmitters: { [key: number]: TinyEmitter<ContextEvents> } = {};
constructor(public transport: Transport) {
//@ts-ignore
private eventTask: Promise<void>;
constructor(public transport: Transport, startEventLoop: boolean) {
super();
this.rpc = new RawClient(this.transport);
this.transport.on("request", (request: Request) => {
const method = request.method;
if (method === "event") {
const event = request.params! as DCWireEvent<Event>;
//@ts-ignore
this.emit(event.event.type, event.contextId, event.event as any);
this.emit("ALL", event.contextId, event.event as any);
if (startEventLoop) {
this.eventTask = this.eventLoop();
}
}
if (this.contextEmitters[event.contextId]) {
this.contextEmitters[event.contextId].emit(
event.event.type,
//@ts-ignore
event.event as any
);
this.contextEmitters[event.contextId].emit("ALL", event.event);
}
async eventLoop(): Promise<void> {
while (true) {
const event = await this.rpc.getNextEvent();
//@ts-ignore
this.emit(event.event.kind, event.contextId, event.event);
this.emit("ALL", event.contextId, event.event);
if (this.contextEmitters[event.contextId]) {
this.contextEmitters[event.contextId].emit(
event.event.kind,
//@ts-ignore
event.event as any
);
this.contextEmitters[event.contextId].emit("ALL", event.event as any);
}
});
}
}
async listAccounts(): Promise<T.Account[]> {
@@ -75,10 +76,12 @@ export class BaseDeltaChat<
export type Opts = {
url: string;
startEventLoop: boolean;
};
export const DEFAULT_OPTS: Opts = {
url: "ws://localhost:20808/ws",
startEventLoop: true,
};
export class DeltaChat extends BaseDeltaChat<WebsocketTransport> {
opts: Opts;
@@ -86,20 +89,24 @@ export class DeltaChat extends BaseDeltaChat<WebsocketTransport> {
this.transport.close();
}
constructor(opts?: Opts | string) {
if (typeof opts === "string") opts = { url: opts };
if (opts) opts = { ...DEFAULT_OPTS, ...opts };
else opts = { ...DEFAULT_OPTS };
if (typeof opts === "string") {
opts = { ...DEFAULT_OPTS, url: opts };
} else if (opts) {
opts = { ...DEFAULT_OPTS, ...opts };
} else {
opts = { ...DEFAULT_OPTS };
}
const transport = new WebsocketTransport(opts.url);
super(transport);
super(transport, opts.startEventLoop);
this.opts = opts;
}
}
export class StdioDeltaChat extends BaseDeltaChat<StdioTransport> {
close() {}
constructor(input: any, output: any) {
constructor(input: any, output: any, startEventLoop: boolean) {
const transport = new StdioTransport(input, output);
super(transport);
super(transport, startEventLoop);
}
}

View File

@@ -1,6 +1,5 @@
export * as RPC from "../generated/jsonrpc.js";
export * as T from "../generated/types.js";
export * from "../generated/events.js";
export { RawClient } from "../generated/client.js";
export * from "./client.js";
export * as yerpc from "yerpc";

View File

@@ -12,7 +12,7 @@ describe("basic tests", () => {
before(async () => {
serverHandle = await startServer();
dc = new DeltaChat(serverHandle.stdin, serverHandle.stdout);
dc = new DeltaChat(serverHandle.stdin, serverHandle.stdout, true);
// dc.on("ALL", (event) => {
//console.log("event", event);
// });
@@ -79,6 +79,9 @@ describe("basic tests", () => {
accountId = await dc.rpc.addAccount();
});
it("should block and unblock contact", async function () {
// Cannot send sync messages to self as we do not have a self address.
await dc.rpc.setConfig(accountId, "sync_msgs", "0");
const contactId = await dc.rpc.createContact(
accountId,
"example@delta.chat",

View File

@@ -13,27 +13,27 @@ describe("online tests", function () {
before(async function () {
this.timeout(60000);
if (!process.env.DCC_NEW_TMP_EMAIL) {
if (!process.env.CHATMAIL_DOMAIN) {
if (process.env.COVERAGE && !process.env.COVERAGE_OFFLINE) {
console.error(
"CAN NOT RUN COVERAGE correctly: Missing DCC_NEW_TMP_EMAIL environment variable!\n\n",
"CAN NOT RUN COVERAGE correctly: Missing CHATMAIL_DOMAIN environment variable!\n\n",
"You can set COVERAGE_OFFLINE=1 to circumvent this check and skip the online tests, but those coverage results will be wrong, because some functions can only be tested in the online test"
);
process.exit(1);
}
console.log(
"Missing DCC_NEW_TMP_EMAIL environment variable!, skip integration tests"
"Missing CHATMAIL_DOMAIN environment variable!, skip integration tests"
);
this.skip();
}
serverHandle = await startServer();
dc = new DeltaChat(serverHandle.stdin, serverHandle.stdout);
dc = new DeltaChat(serverHandle.stdin, serverHandle.stdout, true);
dc.on("ALL", (contextId, { type }) => {
if (type !== "Info") console.log(contextId, type);
dc.on("ALL", (contextId, { kind }) => {
if (kind !== "Info") console.log(contextId, kind);
});
account1 = await createTempUser(process.env.DCC_NEW_TMP_EMAIL);
account1 = createTempUser(process.env.CHATMAIL_DOMAIN);
if (!account1 || !account1.email || !account1.password) {
console.log(
"We didn't got back an account from the api, skip integration tests"
@@ -41,7 +41,7 @@ describe("online tests", function () {
this.skip();
}
account2 = await createTempUser(process.env.DCC_NEW_TMP_EMAIL);
account2 = createTempUser(process.env.CHATMAIL_DOMAIN);
if (!account2 || !account2.email || !account2.password) {
console.log(
"We didn't got back an account2 from the api, skip integration tests"
@@ -148,7 +148,7 @@ describe("online tests", function () {
waitForEvent(dc, "IncomingMsg", accountId1),
]);
dc.rpc.miscSendTextMessage(accountId2, chatId, "super secret message");
// Check if answer arives at A and if it is encrypted
// Check if answer arrives at A and if it is encrypted
await eventPromise2;
const messageId = (
@@ -177,12 +177,12 @@ describe("online tests", function () {
});
});
async function waitForEvent<T extends DcEvent["type"]>(
async function waitForEvent<T extends DcEvent["kind"]>(
dc: DeltaChat,
eventType: T,
accountId: number,
timeout: number = EVENT_TIMEOUT
): Promise<Extract<DcEvent, { type: T }>> {
): Promise<Extract<DcEvent, { kind: T }>> {
return new Promise((resolve, reject) => {
const rejectTimeout = setTimeout(
() => reject(new Error("Timeout reached before event came in")),

View File

@@ -2,7 +2,6 @@ import { tmpdir } from "os";
import { join, resolve } from "path";
import { mkdtemp, rm } from "fs/promises";
import { spawn, exec } from "child_process";
import fetch from "node-fetch";
import { Readable, Writable } from "node:stream";
export type RpcServerHandle = {
@@ -57,15 +56,14 @@ export async function startServer(): Promise<RpcServerHandle> {
};
}
export async function createTempUser(url: string) {
const response = await fetch(url, {
method: "POST",
headers: {
"cache-control": "no-cache",
},
});
if (!response.ok) throw new Error("Received invalid response");
return response.json();
export function createTempUser(chatmailDomain: String) {
const charset = "2345789acdefghjkmnpqrstuvwxyz";
let user = "ci-";
for (let i = 0; i < 6; i++) {
user += charset[Math.floor(Math.random() * charset.length)];
}
const email = user + "@" + chatmailDomain;
return { email: email, password: user + "$" + user };
}
function getTargetDir(): Promise<string> {

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat-repl"
version = "1.111.0"
version = "1.132.1"
license = "MPL-2.0"
edition = "2021"
@@ -8,11 +8,11 @@ edition = "2021"
ansi_term = "0.12.1"
anyhow = "1"
deltachat = { path = "..", features = ["internals"]}
dirs = "4"
log = "0.4.16"
pretty_env_logger = "0.4"
rusqlite = "0.28"
rustyline = "11"
dirs = "5"
log = "0.4.20"
pretty_env_logger = "0.5"
rusqlite = "0.30"
rustyline = "12"
tokio = { version = "1", features = ["fs", "rt-multi-thread", "macros"] }
[features]

View File

@@ -18,6 +18,7 @@ use deltachat::imex::*;
use deltachat::location;
use deltachat::log::LogExt;
use deltachat::message::{self, Message, MessageState, MsgId, Viewtype};
use deltachat::mimeparser::SystemMessage;
use deltachat::peerstate::*;
use deltachat::qr::*;
use deltachat::reaction::send_reaction;
@@ -138,11 +139,7 @@ async fn poke_spec(context: &Context, spec: Option<&str>) -> bool {
/* import a directory */
let dir_name = std::path::Path::new(&real_spec);
let dir = fs::read_dir(dir_name).await;
if dir.is_err() {
error!(context, "Import: Cannot open directory \"{}\".", &real_spec,);
return false;
} else {
let mut dir = dir.unwrap();
if let Ok(mut dir) = dir {
while let Ok(Some(entry)) = dir.next_entry().await {
let name_f = entry.file_name();
let name = name_f.to_string_lossy();
@@ -154,6 +151,9 @@ async fn poke_spec(context: &Context, spec: Option<&str>) -> bool {
}
}
}
} else {
error!(context, "Import: Cannot open directory \"{}\".", &real_spec);
return false;
}
}
println!("Import: {} items read from \"{}\".", read_cnt, &real_spec);
@@ -187,6 +187,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
DownloadState::Available => " [⬇ Download available]",
DownloadState::InProgress => " [⬇ Download in progress...]",
DownloadState::Failure => " [⬇ Download failed]",
DownloadState::Undecipherable => " [⬇ Decryption failed]",
};
let temp2 = timestamp_to_str(msg.get_timestamp());
@@ -199,7 +200,7 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
if msg.has_location() { "📍" } else { "" },
&contact_name,
contact_id,
msgtext.unwrap_or_default(),
msgtext,
if msg.has_html() { "[HAS-HTML]" } else { "" },
if msg.get_from_id() == ContactId::SELF {
""
@@ -210,7 +211,17 @@ async fn log_msg(context: &Context, prefix: impl AsRef<str>, msg: &Message) {
} else {
"[FRESH]"
},
if msg.is_info() { "[INFO]" } else { "" },
if msg.is_info() {
if msg.get_info_type() == SystemMessage::ChatProtectionEnabled {
"[INFO 🛡️]"
} else if msg.get_info_type() == SystemMessage::ChatProtectionDisabled {
"[INFO 🛡️❌]"
} else {
"[INFO]"
}
} else {
""
},
if msg.get_viewtype() == Viewtype::VideochatInvitation {
format!(
"[VIDEOCHAT-INVITATION: {}, type={}]",
@@ -273,13 +284,8 @@ async fn log_contactlist(context: &Context, contacts: &[ContactId]) -> Result<()
let contact = Contact::get_by_id(context, *contact_id).await?;
let name = contact.get_display_name();
let addr = contact.get_addr();
let verified_state = contact.is_verified(context).await?;
let verified_str = if VerifiedStatus::Unverified != verified_state {
if verified_state == VerifiedStatus::BidirectVerified {
" √√"
} else {
""
}
let verified_str = if contact.is_verified(context).await? {
""
} else {
""
};
@@ -395,8 +401,6 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
unpin <chat-id>\n\
mute <chat-id> [<seconds>]\n\
unmute <chat-id>\n\
protect <chat-id>\n\
unprotect <chat-id>\n\
delchat <chat-id>\n\
accept <chat-id>\n\
decline <chat-id>\n\
@@ -563,7 +567,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
context.maybe_network().await;
}
"housekeeping" => {
sql::housekeeping(&context).await.ok_or_log(&context);
sql::housekeeping(&context).await.log_err(&context).ok();
}
"listchats" | "listarchived" | "chats" => {
let listflags = if arg0 == "listarchived" {
@@ -805,15 +809,30 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
}
"chatinfo" => {
ensure!(sel_chat.is_some(), "No chat selected.");
let sel_chat_id = sel_chat.as_ref().unwrap().get_id();
let contacts =
chat::get_chat_contacts(&context, sel_chat.as_ref().unwrap().get_id()).await?;
let contacts = chat::get_chat_contacts(&context, sel_chat_id).await?;
println!("Memberlist:");
log_contactlist(&context, &contacts).await?;
println!("{} contacts", contacts.len());
let similar_chats = sel_chat_id.get_similar_chat_ids(&context).await?;
if !similar_chats.is_empty() {
println!("Similar chats: ");
for (similar_chat_id, metric) in similar_chats {
let similar_chat = Chat::load_from_db(&context, similar_chat_id).await?;
println!(
"{} (#{}) {:.1}",
similar_chat.name,
similar_chat_id,
100.0 * metric
);
}
}
println!(
"{} contacts\nLocation streaming: {}",
contacts.len(),
"Location streaming: {}",
location::is_sending_locations_to_chat(
&context,
Some(sel_chat.as_ref().unwrap().get_id())
@@ -878,7 +897,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let latitude = arg1.parse()?;
let longitude = arg2.parse()?;
let continue_streaming = location::set(&context, latitude, longitude, 0.).await;
let continue_streaming = location::set(&context, latitude, longitude, 0.).await?;
if continue_streaming {
println!("Success, streaming should be continued.");
} else {
@@ -912,9 +931,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
Viewtype::File
});
msg.set_file(arg1, None);
if !arg2.is_empty() {
msg.set_text(Some(arg2.to_string()));
}
msg.set_text(arg2.to_string());
chat::send_msg(&context, sel_chat.as_ref().unwrap().get_id(), &mut msg).await?;
}
"sendhtml" => {
@@ -926,11 +943,11 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
let mut msg = Message::new(Viewtype::Text);
msg.set_html(Some(html.to_string()));
msg.set_text(Some(if arg2.is_empty() {
msg.set_text(if arg2.is_empty() {
path.file_name().unwrap().to_string_lossy().to_string()
} else {
arg2.to_string()
}));
});
chat::send_msg(&context, sel_chat.as_ref().unwrap().get_id(), &mut msg).await?;
}
"sendsyncmsg" => match context.send_sync_msg().await? {
@@ -979,7 +996,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
if !arg1.is_empty() {
let mut draft = Message::new(Viewtype::Text);
draft.set_text(Some(arg1.to_string()));
draft.set_text(arg1.to_string());
sel_chat
.as_ref()
.unwrap()
@@ -1003,7 +1020,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"Please specify text to add as device message."
);
let mut msg = Message::new(Viewtype::Text);
msg.set_text(Some(arg1.to_string()));
msg.set_text(arg1.to_string());
chat::add_device_msg(&context, None, Some(&mut msg)).await?;
}
"listmedia" => {
@@ -1058,20 +1075,6 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
};
chat::set_muted(&context, chat_id, duration).await?;
}
"protect" | "unprotect" => {
ensure!(!arg1.is_empty(), "Argument <chat-id> missing.");
let chat_id = ChatId::new(arg1.parse()?);
chat_id
.set_protection(
&context,
match arg0 {
"protect" => ProtectionStatus::Protected,
"unprotect" => ProtectionStatus::Unprotected,
_ => unreachable!("arg0={:?}", arg0),
},
)
.await?;
}
"delchat" => {
ensure!(!arg1.is_empty(), "Argument <chat-id> missing.");
let chat_id = ChatId::new(arg1.parse()?);
@@ -1090,7 +1093,7 @@ pub async fn cmdline(context: Context, line: &str, chat_id: &mut ChatId) -> Resu
"msginfo" => {
ensure!(!arg1.is_empty(), "Argument <msg-id> missing.");
let id = MsgId::new(arg1.parse()?);
let res = message::get_msg_info(&context, id).await?;
let res = id.get_info(&context).await?;
println!("{res}");
}
"download" => {

View File

@@ -401,7 +401,7 @@ enum ExitResult {
async fn handle_cmd(
line: &str,
ctx: Context,
mut ctx: Context,
selected_chat: &mut ChatId,
) -> Result<ExitResult, Error> {
let mut args = line.splitn(2, ' ');

View File

@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -5,13 +5,27 @@ and provides asynchronous interface to it.
## Getting started
To use Delta Chat RPC client, first build a `deltachat-rpc-server` with `cargo build -p deltachat-rpc-server`.
To use Delta Chat RPC client, first build a `deltachat-rpc-server` with `cargo build -p deltachat-rpc-server`
or download a prebuilt release.
Install it anywhere in your `PATH`.
[Create a virtual environment](https://docs.python.org/3/library/venv.html)
if you don't have one already and activate it.
```
$ python -m venv env
$ . env/bin/activate
```
Install `deltachat-rpc-client` from source:
```
$ cd deltachat-rpc-client
$ pip install .
```
## Testing
1. Build `deltachat-rpc-server` with `cargo build -p deltachat-rpc-server`.
2. Run `PATH="../target/debug:$PATH" tox`.
2. Run `CHATMAIL_DOMAIN=nine.testrun.org PATH="../target/debug:$PATH" tox`.
Additional arguments to `tox` are passed to pytest, e.g. `tox -- -s` does not capture test output.
@@ -23,19 +37,14 @@ $ tox --devenv env
$ . env/bin/activate
```
It is recommended to use IPython, because it supports using `await` directly
from the REPL.
```
$ pip install ipython
$ PATH="../target/debug:$PATH" ipython
...
In [1]: from deltachat_rpc_client import *
In [2]: rpc = Rpc()
In [3]: await rpc.start()
In [4]: dc = DeltaChat(rpc)
In [5]: system_info = await dc.get_system_info()
In [6]: system_info["level"]
Out[6]: 'awesome'
In [7]: await rpc.close()
$ python
>>> from deltachat_rpc_client import *
>>> rpc = Rpc()
>>> rpc.start()
>>> dc = DeltaChat(rpc)
>>> system_info = dc.get_system_info()
>>> system_info["level"]
'awesome'
>>> rpc.close()
```

View File

@@ -4,23 +4,21 @@
it will echo back any text send to it, it also will print to console all Delta Chat core events.
Pass --help to the CLI to see available options.
"""
import asyncio
from deltachat_rpc_client import events, run_bot_cli
hooks = events.HookCollection()
@hooks.on(events.RawEvent)
async def log_event(event):
def log_event(event):
print(event)
@hooks.on(events.NewMessage)
async def echo(event):
def echo(event):
snapshot = event.message_snapshot
await snapshot.chat.send_text(snapshot.text)
snapshot.chat.send_text(snapshot.text)
if __name__ == "__main__":
asyncio.run(run_bot_cli(hooks))
run_bot_cli(hooks)

44
deltachat-rpc-client/examples/echobot_advanced.py Normal file → Executable file
View File

@@ -3,9 +3,9 @@
it will echo back any message that has non-empty text and also supports the /help command.
"""
import asyncio
import logging
import sys
from threading import Thread
from deltachat_rpc_client import Bot, DeltaChat, EventType, Rpc, events
@@ -13,62 +13,62 @@ hooks = events.HookCollection()
@hooks.on(events.RawEvent)
async def log_event(event):
if event.type == EventType.INFO:
def log_event(event):
if event.kind == EventType.INFO:
logging.info(event.msg)
elif event.type == EventType.WARNING:
elif event.kind == EventType.WARNING:
logging.warning(event.msg)
@hooks.on(events.RawEvent(EventType.ERROR))
async def log_error(event):
def log_error(event):
logging.error(event.msg)
@hooks.on(events.MemberListChanged)
async def on_memberlist_changed(event):
def on_memberlist_changed(event):
logging.info("member %s was %s", event.member, "added" if event.member_added else "removed")
@hooks.on(events.GroupImageChanged)
async def on_group_image_changed(event):
def on_group_image_changed(event):
logging.info("group image %s", "deleted" if event.image_deleted else "changed")
@hooks.on(events.GroupNameChanged)
async def on_group_name_changed(event):
def on_group_name_changed(event):
logging.info("group name changed, old name: %s", event.old_name)
@hooks.on(events.NewMessage(func=lambda e: not e.command))
async def echo(event):
def echo(event):
snapshot = event.message_snapshot
if snapshot.text or snapshot.file:
await snapshot.chat.send_message(text=snapshot.text, file=snapshot.file)
snapshot.chat.send_message(text=snapshot.text, file=snapshot.file)
@hooks.on(events.NewMessage(command="/help"))
async def help_command(event):
def help_command(event):
snapshot = event.message_snapshot
await snapshot.chat.send_text("Send me any message and I will echo it back")
snapshot.chat.send_text("Send me any message and I will echo it back")
async def main():
async with Rpc() as rpc:
def main():
with Rpc() as rpc:
deltachat = DeltaChat(rpc)
system_info = await deltachat.get_system_info()
system_info = deltachat.get_system_info()
logging.info("Running deltachat core %s", system_info.deltachat_core_version)
accounts = await deltachat.get_all_accounts()
account = accounts[0] if accounts else await deltachat.add_account()
accounts = deltachat.get_all_accounts()
account = accounts[0] if accounts else deltachat.add_account()
bot = Bot(account, hooks)
if not await bot.is_configured():
# Save a reference to avoid garbage collection of the task.
_configure_task = asyncio.create_task(bot.configure(email=sys.argv[1], password=sys.argv[2]))
await bot.run_forever()
if not bot.is_configured():
configure_thread = Thread(run=bot.configure, kwargs={"email": sys.argv[1], "password": sys.argv[2]})
configure_thread.start()
bot.run_forever()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
main()

53
deltachat-rpc-client/examples/echobot_no_hooks.py Normal file → Executable file
View File

@@ -2,56 +2,55 @@
"""
Example echo bot without using hooks
"""
import asyncio
import logging
import sys
from deltachat_rpc_client import DeltaChat, EventType, Rpc
from deltachat_rpc_client import DeltaChat, EventType, Rpc, SpecialContactId
async def main():
async with Rpc() as rpc:
def main():
with Rpc() as rpc:
deltachat = DeltaChat(rpc)
system_info = await deltachat.get_system_info()
system_info = deltachat.get_system_info()
logging.info("Running deltachat core %s", system_info["deltachat_core_version"])
accounts = await deltachat.get_all_accounts()
account = accounts[0] if accounts else await deltachat.add_account()
accounts = deltachat.get_all_accounts()
account = accounts[0] if accounts else deltachat.add_account()
await account.set_config("bot", "1")
if not await account.is_configured():
account.set_config("bot", "1")
if not account.is_configured():
logging.info("Account is not configured, configuring")
await account.set_config("addr", sys.argv[1])
await account.set_config("mail_pw", sys.argv[2])
await account.configure()
account.set_config("addr", sys.argv[1])
account.set_config("mail_pw", sys.argv[2])
account.configure()
logging.info("Configured")
else:
logging.info("Account is already configured")
await deltachat.start_io()
deltachat.start_io()
async def process_messages():
for message in await account.get_fresh_messages_in_arrival_order():
snapshot = await message.get_snapshot()
if not snapshot.is_bot and not snapshot.is_info:
await snapshot.chat.send_text(snapshot.text)
await snapshot.message.mark_seen()
def process_messages():
for message in account.get_next_messages():
snapshot = message.get_snapshot()
if snapshot.from_id != SpecialContactId.SELF and not snapshot.is_bot and not snapshot.is_info:
snapshot.chat.send_text(snapshot.text)
snapshot.message.mark_seen()
# Process old messages.
await process_messages()
process_messages()
while True:
event = await account.wait_for_event()
if event["type"] == EventType.INFO:
event = account.wait_for_event()
if event["kind"] == EventType.INFO:
logging.info("%s", event["msg"])
elif event["type"] == EventType.WARNING:
elif event["kind"] == EventType.WARNING:
logging.warning("%s", event["msg"])
elif event["type"] == EventType.ERROR:
elif event["kind"] == EventType.ERROR:
logging.error("%s", event["msg"])
elif event["type"] == EventType.INCOMING_MSG:
elif event["kind"] == EventType.INCOMING_MSG:
logging.info("Got an incoming message")
await process_messages()
process_messages()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())
main()

View File

@@ -5,9 +5,19 @@ build-backend = "setuptools.build_meta"
[project]
name = "deltachat-rpc-client"
description = "Python client for Delta Chat core JSON-RPC interface"
dependencies = [
"aiohttp",
"aiodns"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Topic :: Communications :: Chat",
"Topic :: Communications :: Email"
]
dynamic = [
"version"
@@ -21,6 +31,9 @@ deltachat_rpc_client = [
[project.entry-points.pytest11]
"deltachat_rpc_client.pytestplugin" = "deltachat_rpc_client.pytestplugin"
[tool.setuptools_scm]
root = ".."
[tool.black]
line-length = 120

View File

@@ -1,9 +1,9 @@
"""Delta Chat asynchronous high-level API"""
"""Delta Chat JSON-RPC high-level API"""
from ._utils import AttrDict, run_bot_cli, run_client_cli
from .account import Account
from .chat import Chat
from .client import Bot, Client
from .const import EventType
from .const import EventType, SpecialContactId
from .contact import Contact
from .deltachat import DeltaChat
from .message import Message
@@ -19,6 +19,7 @@ __all__ = [
"DeltaChat",
"EventType",
"Message",
"SpecialContactId",
"Rpc",
"run_bot_cli",
"run_client_cli",

View File

@@ -1,7 +1,7 @@
import argparse
import asyncio
import re
import sys
from threading import Thread
from typing import TYPE_CHECKING, Callable, Iterable, Optional, Tuple, Type, Union
if TYPE_CHECKING:
@@ -43,7 +43,7 @@ class AttrDict(dict):
super().__setattr__(attr, val)
async def run_client_cli(
def run_client_cli(
hooks: Optional[Iterable[Tuple[Callable, Union[type, "EventFilter"]]]] = None,
argv: Optional[list] = None,
**kwargs,
@@ -54,10 +54,10 @@ async def run_client_cli(
"""
from .client import Client
await _run_cli(Client, hooks, argv, **kwargs)
_run_cli(Client, hooks, argv, **kwargs)
async def run_bot_cli(
def run_bot_cli(
hooks: Optional[Iterable[Tuple[Callable, Union[type, "EventFilter"]]]] = None,
argv: Optional[list] = None,
**kwargs,
@@ -68,10 +68,10 @@ async def run_bot_cli(
"""
from .client import Bot
await _run_cli(Bot, hooks, argv, **kwargs)
_run_cli(Bot, hooks, argv, **kwargs)
async def _run_cli(
def _run_cli(
client_type: Type["Client"],
hooks: Optional[Iterable[Tuple[Callable, Union[type, "EventFilter"]]]] = None,
argv: Optional[list] = None,
@@ -93,20 +93,20 @@ async def _run_cli(
parser.add_argument("--password", action="store", help="password")
args = parser.parse_args(argv[1:])
async with Rpc(accounts_dir=args.accounts_dir, **kwargs) as rpc:
with Rpc(accounts_dir=args.accounts_dir, **kwargs) as rpc:
deltachat = DeltaChat(rpc)
core_version = (await deltachat.get_system_info()).deltachat_core_version
accounts = await deltachat.get_all_accounts()
account = accounts[0] if accounts else await deltachat.add_account()
core_version = (deltachat.get_system_info()).deltachat_core_version
accounts = deltachat.get_all_accounts()
account = accounts[0] if accounts else deltachat.add_account()
client = client_type(account, hooks)
client.logger.debug("Running deltachat core %s", core_version)
if not await client.is_configured():
if not client.is_configured():
assert args.email, "Account is not configured and email must be provided"
assert args.password, "Account is not configured and password must be provided"
# Save a reference to avoid garbage collection of the task.
_configure_task = asyncio.create_task(client.configure(email=args.email, password=args.password))
await client.run_forever()
configure_thread = Thread(run=client.configure, kwargs={"email": args.email, "password": args.password})
configure_thread.start()
client.run_forever()
def extract_addr(text: str) -> str:

View File

@@ -1,9 +1,10 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
from warnings import warn
from ._utils import AttrDict
from .chat import Chat
from .const import ChatlistFlag, ContactFlag, SpecialContactId
from .const import ChatlistFlag, ContactFlag, EventType, SpecialContactId
from .contact import Contact
from .message import Message
@@ -23,63 +24,63 @@ class Account:
def _rpc(self) -> "Rpc":
return self.manager.rpc
async def wait_for_event(self) -> AttrDict:
def wait_for_event(self) -> AttrDict:
"""Wait until the next event and return it."""
return AttrDict(await self._rpc.wait_for_event(self.id))
return AttrDict(self._rpc.wait_for_event(self.id))
async def remove(self) -> None:
def remove(self) -> None:
"""Remove the account."""
await self._rpc.remove_account(self.id)
self._rpc.remove_account(self.id)
async def start_io(self) -> None:
def start_io(self) -> None:
"""Start the account I/O."""
await self._rpc.start_io(self.id)
self._rpc.start_io(self.id)
async def stop_io(self) -> None:
def stop_io(self) -> None:
"""Stop the account I/O."""
await self._rpc.stop_io(self.id)
self._rpc.stop_io(self.id)
async def get_info(self) -> AttrDict:
def get_info(self) -> AttrDict:
"""Return dictionary of this account configuration parameters."""
return AttrDict(await self._rpc.get_info(self.id))
return AttrDict(self._rpc.get_info(self.id))
async def get_size(self) -> int:
def get_size(self) -> int:
"""Get the combined filesize of an account in bytes."""
return await self._rpc.get_account_file_size(self.id)
return self._rpc.get_account_file_size(self.id)
async def is_configured(self) -> bool:
def is_configured(self) -> bool:
"""Return True if this account is configured."""
return await self._rpc.is_configured(self.id)
return self._rpc.is_configured(self.id)
async def set_config(self, key: str, value: Optional[str] = None) -> None:
def set_config(self, key: str, value: Optional[str] = None) -> None:
"""Set configuration value."""
await self._rpc.set_config(self.id, key, value)
self._rpc.set_config(self.id, key, value)
async def get_config(self, key: str) -> Optional[str]:
def get_config(self, key: str) -> Optional[str]:
"""Get configuration value."""
return await self._rpc.get_config(self.id, key)
return self._rpc.get_config(self.id, key)
async def update_config(self, **kwargs) -> None:
def update_config(self, **kwargs) -> None:
"""update config values."""
for key, value in kwargs.items():
await self.set_config(key, value)
self.set_config(key, value)
async def set_avatar(self, img_path: Optional[str] = None) -> None:
def set_avatar(self, img_path: Optional[str] = None) -> None:
"""Set self avatar.
Passing None will discard the currently set avatar.
"""
await self.set_config("selfavatar", img_path)
self.set_config("selfavatar", img_path)
async def get_avatar(self) -> Optional[str]:
def get_avatar(self) -> Optional[str]:
"""Get self avatar."""
return await self.get_config("selfavatar")
return self.get_config("selfavatar")
async def configure(self) -> None:
def configure(self) -> None:
"""Configure an account."""
await self._rpc.configure(self.id)
self._rpc.configure(self.id)
async def create_contact(self, obj: Union[int, str, Contact], name: Optional[str] = None) -> Contact:
def create_contact(self, obj: Union[int, str, Contact], name: Optional[str] = None) -> Contact:
"""Create a new Contact or return an existing one.
Calling this method will always result in the same
@@ -93,24 +94,38 @@ class Account:
if isinstance(obj, int):
obj = Contact(self, obj)
if isinstance(obj, Contact):
obj = (await obj.get_snapshot()).address
return Contact(self, await self._rpc.create_contact(self.id, obj, name))
obj = obj.get_snapshot().address
return Contact(self, self._rpc.create_contact(self.id, obj, name))
def get_contact_by_id(self, contact_id: int) -> Contact:
"""Return Contact instance for the given contact ID."""
return Contact(self, contact_id)
async def get_contact_by_addr(self, address: str) -> Optional[Contact]:
def get_contact_by_addr(self, address: str) -> Optional[Contact]:
"""Check if an e-mail address belongs to a known and unblocked contact."""
contact_id = await self._rpc.lookup_contact_id_by_addr(self.id, address)
contact_id = self._rpc.lookup_contact_id_by_addr(self.id, address)
return contact_id and Contact(self, contact_id)
async def get_blocked_contacts(self) -> List[AttrDict]:
def get_blocked_contacts(self) -> List[AttrDict]:
"""Return a list with snapshots of all blocked contacts."""
contacts = await self._rpc.get_blocked_contacts(self.id)
contacts = self._rpc.get_blocked_contacts(self.id)
return [AttrDict(contact=Contact(self, contact["id"]), **contact) for contact in contacts]
async def get_contacts(
def get_chat_by_contact(self, contact: Union[int, Contact]) -> Optional[Chat]:
"""Return 1:1 chat for a contact if it exists."""
if isinstance(contact, Contact):
assert contact.account == self
contact_id = contact.id
elif isinstance(contact, int):
contact_id = contact
else:
raise ValueError(f"{contact!r} is not a contact")
chat_id = self._rpc.get_chat_id_by_contact_id(self.id, contact_id)
if chat_id:
return Chat(self, chat_id)
return None
def get_contacts(
self,
query: Optional[str] = None,
with_self: bool = False,
@@ -132,9 +147,9 @@ class Account:
flags |= ContactFlag.ADD_SELF
if snapshot:
contacts = await self._rpc.get_contacts(self.id, flags, query)
contacts = self._rpc.get_contacts(self.id, flags, query)
return [AttrDict(contact=Contact(self, contact["id"]), **contact) for contact in contacts]
contacts = await self._rpc.get_contact_ids(self.id, flags, query)
contacts = self._rpc.get_contact_ids(self.id, flags, query)
return [Contact(self, contact_id) for contact_id in contacts]
@property
@@ -142,7 +157,7 @@ class Account:
"""This account's identity as a Contact."""
return Contact(self, SpecialContactId.SELF)
async def get_chatlist(
def get_chatlist(
self,
query: Optional[str] = None,
contact: Optional[Contact] = None,
@@ -174,72 +189,124 @@ class Account:
if alldone_hint:
flags |= ChatlistFlag.ADD_ALLDONE_HINT
entries = await self._rpc.get_chatlist_entries(self.id, flags, query, contact and contact.id)
entries = self._rpc.get_chatlist_entries(self.id, flags, query, contact and contact.id)
if not snapshot:
return [Chat(self, entry[0]) for entry in entries]
return [Chat(self, entry) for entry in entries]
items = await self._rpc.get_chatlist_items_by_entries(self.id, entries)
items = self._rpc.get_chatlist_items_by_entries(self.id, entries)
chats = []
for item in items.values():
item["chat"] = Chat(self, item["id"])
chats.append(AttrDict(item))
return chats
async def create_group(self, name: str, protect: bool = False) -> Chat:
def create_group(self, name: str, protect: bool = False) -> Chat:
"""Create a new group chat.
After creation, the group has only self-contact as member and is in unpromoted state.
"""
return Chat(self, await self._rpc.create_group_chat(self.id, name, protect))
return Chat(self, self._rpc.create_group_chat(self.id, name, protect))
def get_chat_by_id(self, chat_id: int) -> Chat:
"""Return the Chat instance with the given ID."""
return Chat(self, chat_id)
async def secure_join(self, qrdata: str) -> Chat:
def secure_join(self, qrdata: str) -> Chat:
"""Continue a Setup-Contact or Verified-Group-Invite protocol started on
another device.
The function returns immediately and the handshake runs in background, sending
and receiving several messages.
Subsequent calls of `secure_join()` will abort previous, unfinished handshakes.
See https://countermitm.readthedocs.io/en/latest/new.html for protocol details.
See https://securejoin.readthedocs.io/en/latest/new.html for protocol details.
:param qrdata: The text of the scanned QR code.
"""
return Chat(self, await self._rpc.secure_join(self.id, qrdata))
return Chat(self, self._rpc.secure_join(self.id, qrdata))
async def get_qr_code(self) -> Tuple[str, str]:
def get_qr_code(self) -> Tuple[str, str]:
"""Get Setup-Contact QR Code text and SVG data.
this data needs to be transferred to another Delta Chat account
in a second channel, typically used by mobiles with QRcode-show + scan UX.
"""
return await self._rpc.get_chat_securejoin_qr_code_svg(self.id, None)
return self._rpc.get_chat_securejoin_qr_code_svg(self.id, None)
def get_message_by_id(self, msg_id: int) -> Message:
"""Return the Message instance with the given ID."""
return Message(self, msg_id)
async def mark_seen_messages(self, messages: List[Message]) -> None:
def mark_seen_messages(self, messages: List[Message]) -> None:
"""Mark the given set of messages as seen."""
await self._rpc.markseen_msgs(self.id, [msg.id for msg in messages])
self._rpc.markseen_msgs(self.id, [msg.id for msg in messages])
async def delete_messages(self, messages: List[Message]) -> None:
def delete_messages(self, messages: List[Message]) -> None:
"""Delete messages (local and remote)."""
await self._rpc.delete_messages(self.id, [msg.id for msg in messages])
self._rpc.delete_messages(self.id, [msg.id for msg in messages])
async def get_fresh_messages(self) -> List[Message]:
def get_fresh_messages(self) -> List[Message]:
"""Return the list of fresh messages, newest messages first.
This call is intended for displaying notifications.
If you are writing a bot, use `get_fresh_messages_in_arrival_order()` instead,
to process oldest messages first.
"""
fresh_msg_ids = await self._rpc.get_fresh_msgs(self.id)
fresh_msg_ids = self._rpc.get_fresh_msgs(self.id)
return [Message(self, msg_id) for msg_id in fresh_msg_ids]
async def get_fresh_messages_in_arrival_order(self) -> List[Message]:
def get_next_messages(self) -> List[Message]:
"""Return a list of next messages."""
next_msg_ids = self._rpc.get_next_msgs(self.id)
return [Message(self, msg_id) for msg_id in next_msg_ids]
def wait_next_messages(self) -> List[Message]:
"""Wait for new messages and return a list of them."""
next_msg_ids = self._rpc.wait_next_msgs(self.id)
return [Message(self, msg_id) for msg_id in next_msg_ids]
def wait_for_incoming_msg_event(self):
"""Wait for incoming message event and return it."""
while True:
event = self.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
return event
def wait_for_securejoin_inviter_success(self):
while True:
event = self.wait_for_event()
if event["kind"] == "SecurejoinInviterProgress" and event["progress"] == 1000:
break
def wait_for_securejoin_joiner_success(self):
while True:
event = self.wait_for_event()
if event["kind"] == "SecurejoinJoinerProgress" and event["progress"] == 1000:
break
def get_fresh_messages_in_arrival_order(self) -> List[Message]:
"""Return fresh messages list sorted in the order of their arrival, with ascending IDs."""
fresh_msg_ids = sorted(await self._rpc.get_fresh_msgs(self.id))
warn(
"get_fresh_messages_in_arrival_order is deprecated, use get_next_messages instead.",
DeprecationWarning,
stacklevel=2,
)
fresh_msg_ids = sorted(self._rpc.get_fresh_msgs(self.id))
return [Message(self, msg_id) for msg_id in fresh_msg_ids]
def export_backup(self, path, passphrase: str = "") -> None:
"""Export backup."""
self._rpc.export_backup(self.id, str(path), passphrase)
def import_backup(self, path, passphrase: str = "") -> None:
"""Import backup."""
self._rpc.import_backup(self.id, str(path), passphrase)
def export_self_keys(self, path) -> None:
"""Export keys."""
passphrase = "" # Setting passphrase is currently not supported.
self._rpc.export_self_keys(self.id, str(path), passphrase)
def import_self_keys(self, path) -> None:
"""Import keys."""
passphrase = "" # Importing passphrase-protected keys is currently not supported.
self._rpc.import_self_keys(self.id, str(path), passphrase)

View File

@@ -25,7 +25,7 @@ class Chat:
def _rpc(self) -> "Rpc":
return self.account._rpc
async def delete(self) -> None:
def delete(self) -> None:
"""Delete this chat and all its messages.
Note:
@@ -33,79 +33,83 @@ class Chat:
- does not delete messages on server
- the chat or contact is not blocked, new message will arrive
"""
await self._rpc.delete_chat(self.account.id, self.id)
self._rpc.delete_chat(self.account.id, self.id)
async def block(self) -> None:
def block(self) -> None:
"""Block this chat."""
await self._rpc.block_chat(self.account.id, self.id)
self._rpc.block_chat(self.account.id, self.id)
async def accept(self) -> None:
def accept(self) -> None:
"""Accept this contact request chat."""
await self._rpc.accept_chat(self.account.id, self.id)
self._rpc.accept_chat(self.account.id, self.id)
async def leave(self) -> None:
def leave(self) -> None:
"""Leave this chat."""
await self._rpc.leave_group(self.account.id, self.id)
self._rpc.leave_group(self.account.id, self.id)
async def mute(self, duration: Optional[int] = None) -> None:
def mute(self, duration: Optional[int] = None) -> None:
"""Mute this chat, if a duration is not provided the chat is muted forever.
:param duration: mute duration from now in seconds. Must be greater than zero.
"""
if duration is not None:
assert duration > 0, "Invalid duration"
dur: Union[str, dict] = {"Until": duration}
dur: dict = {"kind": "Until", "duration": duration}
else:
dur = "Forever"
await self._rpc.set_chat_mute_duration(self.account.id, self.id, dur)
dur = {"kind": "Forever"}
self._rpc.set_chat_mute_duration(self.account.id, self.id, dur)
async def unmute(self) -> None:
def unmute(self) -> None:
"""Unmute this chat."""
await self._rpc.set_chat_mute_duration(self.account.id, self.id, "NotMuted")
self._rpc.set_chat_mute_duration(self.account.id, self.id, {"kind": "NotMuted"})
async def pin(self) -> None:
def pin(self) -> None:
"""Pin this chat."""
await self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.PINNED)
self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.PINNED)
async def unpin(self) -> None:
def unpin(self) -> None:
"""Unpin this chat."""
await self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.NORMAL)
self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.NORMAL)
async def archive(self) -> None:
def archive(self) -> None:
"""Archive this chat."""
await self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.ARCHIVED)
self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.ARCHIVED)
async def unarchive(self) -> None:
def unarchive(self) -> None:
"""Unarchive this chat."""
await self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.NORMAL)
self._rpc.set_chat_visibility(self.account.id, self.id, ChatVisibility.NORMAL)
async def set_name(self, name: str) -> None:
def set_name(self, name: str) -> None:
"""Set name of this chat."""
await self._rpc.set_chat_name(self.account.id, self.id, name)
self._rpc.set_chat_name(self.account.id, self.id, name)
async def set_ephemeral_timer(self, timer: int) -> None:
def set_ephemeral_timer(self, timer: int) -> None:
"""Set ephemeral timer of this chat."""
await self._rpc.set_chat_ephemeral_timer(self.account.id, self.id, timer)
self._rpc.set_chat_ephemeral_timer(self.account.id, self.id, timer)
async def get_encryption_info(self) -> str:
def get_encryption_info(self) -> str:
"""Return encryption info for this chat."""
return await self._rpc.get_chat_encryption_info(self.account.id, self.id)
return self._rpc.get_chat_encryption_info(self.account.id, self.id)
async def get_qr_code(self) -> Tuple[str, str]:
def get_qr_code(self) -> Tuple[str, str]:
"""Get Join-Group QR code text and SVG data."""
return await self._rpc.get_chat_securejoin_qr_code_svg(self.account.id, self.id)
return self._rpc.get_chat_securejoin_qr_code_svg(self.account.id, self.id)
async def get_basic_snapshot(self) -> AttrDict:
def get_basic_snapshot(self) -> AttrDict:
"""Get a chat snapshot with basic info about this chat."""
info = await self._rpc.get_basic_chat_info(self.account.id, self.id)
info = self._rpc.get_basic_chat_info(self.account.id, self.id)
return AttrDict(chat=self, **info)
async def get_full_snapshot(self) -> AttrDict:
def get_full_snapshot(self) -> AttrDict:
"""Get a full snapshot of this chat."""
info = await self._rpc.get_full_chat_by_id(self.account.id, self.id)
info = self._rpc.get_full_chat_by_id(self.account.id, self.id)
return AttrDict(chat=self, **info)
async def send_message(
def can_send(self) -> bool:
"""Return true if messages can be sent to the chat."""
return self._rpc.can_send(self.account.id, self.id)
def send_message(
self,
text: Optional[str] = None,
html: Optional[str] = None,
@@ -126,49 +130,50 @@ class Chat:
"file": file,
"location": location,
"overrideSenderName": override_sender_name,
"quotedMsg": quoted_msg,
"quotedMessageId": quoted_msg,
}
msg_id = await self._rpc.send_msg(self.account.id, self.id, draft)
msg_id = self._rpc.send_msg(self.account.id, self.id, draft)
return Message(self.account, msg_id)
async def send_text(self, text: str) -> Message:
def send_text(self, text: str) -> Message:
"""Send a text message and return the resulting Message instance."""
msg_id = await self._rpc.misc_send_text_message(self.account.id, self.id, text)
msg_id = self._rpc.misc_send_text_message(self.account.id, self.id, text)
return Message(self.account, msg_id)
async def send_videochat_invitation(self) -> Message:
def send_videochat_invitation(self) -> Message:
"""Send a videochat invitation and return the resulting Message instance."""
msg_id = await self._rpc.send_videochat_invitation(self.account.id, self.id)
msg_id = self._rpc.send_videochat_invitation(self.account.id, self.id)
return Message(self.account, msg_id)
async def send_sticker(self, path: str) -> Message:
def send_sticker(self, path: str) -> Message:
"""Send an sticker and return the resulting Message instance."""
msg_id = await self._rpc.send_sticker(self.account.id, self.id, path)
msg_id = self._rpc.send_sticker(self.account.id, self.id, path)
return Message(self.account, msg_id)
async def forward_messages(self, messages: List[Message]) -> None:
def forward_messages(self, messages: List[Message]) -> None:
"""Forward a list of messages to this chat."""
msg_ids = [msg.id for msg in messages]
await self._rpc.forward_messages(self.account.id, msg_ids, self.id)
self._rpc.forward_messages(self.account.id, msg_ids, self.id)
async def set_draft(
def set_draft(
self,
text: Optional[str] = None,
file: Optional[str] = None,
quoted_msg: Optional[int] = None,
viewtype: Optional[str] = None,
) -> None:
"""Set draft message."""
if isinstance(quoted_msg, Message):
quoted_msg = quoted_msg.id
await self._rpc.misc_set_draft(self.account.id, self.id, text, file, quoted_msg)
self._rpc.misc_set_draft(self.account.id, self.id, text, file, quoted_msg, viewtype)
async def remove_draft(self) -> None:
def remove_draft(self) -> None:
"""Remove draft message."""
await self._rpc.remove_draft(self.account.id, self.id)
self._rpc.remove_draft(self.account.id, self.id)
async def get_draft(self) -> Optional[AttrDict]:
def get_draft(self) -> Optional[AttrDict]:
"""Get draft message."""
snapshot = await self._rpc.get_draft(self.account.id, self.id)
snapshot = self._rpc.get_draft(self.account.id, self.id)
if not snapshot:
return None
snapshot = AttrDict(snapshot)
@@ -177,61 +182,61 @@ class Chat:
snapshot["message"] = Message(self.account, snapshot.id)
return snapshot
async def get_messages(self, info_only: bool = False, add_daymarker: bool = False) -> List[Message]:
def get_messages(self, info_only: bool = False, add_daymarker: bool = False) -> List[Message]:
"""get the list of messages in this chat."""
msgs = await self._rpc.get_message_ids(self.account.id, self.id, info_only, add_daymarker)
msgs = self._rpc.get_message_ids(self.account.id, self.id, info_only, add_daymarker)
return [Message(self.account, msg_id) for msg_id in msgs]
async def get_fresh_message_count(self) -> int:
def get_fresh_message_count(self) -> int:
"""Get number of fresh messages in this chat"""
return await self._rpc.get_fresh_msg_cnt(self.account.id, self.id)
return self._rpc.get_fresh_msg_cnt(self.account.id, self.id)
async def mark_noticed(self) -> None:
def mark_noticed(self) -> None:
"""Mark all messages in this chat as noticed."""
await self._rpc.marknoticed_chat(self.account.id, self.id)
self._rpc.marknoticed_chat(self.account.id, self.id)
async def add_contact(self, *contact: Union[int, str, Contact]) -> None:
def add_contact(self, *contact: Union[int, str, Contact]) -> None:
"""Add contacts to this group."""
for cnt in contact:
if isinstance(cnt, str):
contact_id = (await self.account.create_contact(cnt)).id
contact_id = self.account.create_contact(cnt).id
elif not isinstance(cnt, int):
contact_id = cnt.id
else:
contact_id = cnt
await self._rpc.add_contact_to_chat(self.account.id, self.id, contact_id)
self._rpc.add_contact_to_chat(self.account.id, self.id, contact_id)
async def remove_contact(self, *contact: Union[int, str, Contact]) -> None:
def remove_contact(self, *contact: Union[int, str, Contact]) -> None:
"""Remove members from this group."""
for cnt in contact:
if isinstance(cnt, str):
contact_id = (await self.account.create_contact(cnt)).id
contact_id = self.account.create_contact(cnt).id
elif not isinstance(cnt, int):
contact_id = cnt.id
else:
contact_id = cnt
await self._rpc.remove_contact_from_chat(self.account.id, self.id, contact_id)
self._rpc.remove_contact_from_chat(self.account.id, self.id, contact_id)
async def get_contacts(self) -> List[Contact]:
def get_contacts(self) -> List[Contact]:
"""Get the contacts belonging to this chat.
For single/direct chats self-address is not included.
"""
contacts = await self._rpc.get_chat_contacts(self.account.id, self.id)
contacts = self._rpc.get_chat_contacts(self.account.id, self.id)
return [Contact(self.account, contact_id) for contact_id in contacts]
async def set_image(self, path: str) -> None:
def set_image(self, path: str) -> None:
"""Set profile image of this chat.
:param path: Full path of the image to use as the group image.
"""
await self._rpc.set_chat_profile_image(self.account.id, self.id, path)
self._rpc.set_chat_profile_image(self.account.id, self.id, path)
async def remove_image(self) -> None:
def remove_image(self) -> None:
"""Remove profile image of this chat."""
await self._rpc.set_chat_profile_image(self.account.id, self.id, None)
self._rpc.set_chat_profile_image(self.account.id, self.id, None)
async def get_locations(
def get_locations(
self,
contact: Optional[Contact] = None,
timestamp_from: Optional["datetime"] = None,
@@ -242,7 +247,7 @@ class Chat:
time_to = calendar.timegm(timestamp_to.utctimetuple()) if timestamp_to else 0
contact_id = contact.id if contact else 0
result = await self._rpc.get_locations(self.account.id, self.id, contact_id, time_from, time_to)
result = self._rpc.get_locations(self.account.id, self.id, contact_id, time_from, time_to)
locations = []
contacts: Dict[int, Contact] = {}
for loc in result:

View File

@@ -1,10 +1,8 @@
"""Event loop implementations offering high level event handling/hooking."""
import inspect
import logging
from typing import (
TYPE_CHECKING,
Callable,
Coroutine,
Dict,
Iterable,
Optional,
@@ -20,7 +18,7 @@ from ._utils import (
parse_system_image_changed,
parse_system_title_changed,
)
from .const import COMMAND_PREFIX, EventType, SystemMessageType
from .const import COMMAND_PREFIX, EventType, SpecialContactId, SystemMessageType
from .events import (
EventFilter,
GroupImageChanged,
@@ -78,22 +76,22 @@ class Client:
)
self._hooks.get(type(event), set()).remove((hook, event))
async def is_configured(self) -> bool:
return await self.account.is_configured()
def is_configured(self) -> bool:
return self.account.is_configured()
async def configure(self, email: str, password: str, **kwargs) -> None:
await self.account.set_config("addr", email)
await self.account.set_config("mail_pw", password)
def configure(self, email: str, password: str, **kwargs) -> None:
self.account.set_config("addr", email)
self.account.set_config("mail_pw", password)
for key, value in kwargs.items():
await self.account.set_config(key, value)
await self.account.configure()
self.account.set_config(key, value)
self.account.configure()
self.logger.debug("Account configured")
async def run_forever(self) -> None:
def run_forever(self) -> None:
"""Process events forever."""
await self.run_until(lambda _: False)
self.run_until(lambda _: False)
async def run_until(self, func: Callable[[AttrDict], Union[bool, Coroutine]]) -> AttrDict:
def run_until(self, func: Callable[[AttrDict], bool]) -> AttrDict:
"""Process events until the given callable evaluates to True.
The callable should accept an AttrDict object representing the
@@ -101,39 +99,37 @@ class Client:
evaluates to True.
"""
self.logger.debug("Listening to incoming events...")
if await self.is_configured():
await self.account.start_io()
await self._process_messages() # Process old messages.
if self.is_configured():
self.account.start_io()
self._process_messages() # Process old messages.
while True:
event = await self.account.wait_for_event()
event["type"] = EventType(event.type)
event = self.account.wait_for_event()
event["kind"] = EventType(event.kind)
event["account"] = self.account
await self._on_event(event)
if event.type == EventType.INCOMING_MSG:
await self._process_messages()
self._on_event(event)
if event.kind == EventType.INCOMING_MSG:
self._process_messages()
stop = func(event)
if inspect.isawaitable(stop):
stop = await stop
if stop:
return event
async def _on_event(self, event: AttrDict, filter_type: Type[EventFilter] = RawEvent) -> None:
def _on_event(self, event: AttrDict, filter_type: Type[EventFilter] = RawEvent) -> None:
for hook, evfilter in self._hooks.get(filter_type, []):
if await evfilter.filter(event):
if evfilter.filter(event):
try:
await hook(event)
hook(event)
except Exception as ex:
self.logger.exception(ex)
async def _parse_command(self, event: AttrDict) -> None:
def _parse_command(self, event: AttrDict) -> None:
cmds = [hook[1].command for hook in self._hooks.get(NewMessage, []) if hook[1].command]
parts = event.message_snapshot.text.split(maxsplit=1)
payload = parts[1] if len(parts) > 1 else ""
cmd = parts.pop(0)
if "@" in cmd:
suffix = "@" + (await self.account.self_contact.get_snapshot()).address
suffix = "@" + self.account.self_contact.get_snapshot().address
if cmd.endswith(suffix):
cmd = cmd[: -len(suffix)]
else:
@@ -153,32 +149,32 @@ class Client:
event["command"], event["payload"] = cmd, payload
async def _on_new_msg(self, snapshot: AttrDict) -> None:
def _on_new_msg(self, snapshot: AttrDict) -> None:
event = AttrDict(command="", payload="", message_snapshot=snapshot)
if not snapshot.is_info and snapshot.text.startswith(COMMAND_PREFIX):
await self._parse_command(event)
await self._on_event(event, NewMessage)
self._parse_command(event)
self._on_event(event, NewMessage)
async def _handle_info_msg(self, snapshot: AttrDict) -> None:
def _handle_info_msg(self, snapshot: AttrDict) -> None:
event = AttrDict(message_snapshot=snapshot)
img_changed = parse_system_image_changed(snapshot.text)
if img_changed:
_, event["image_deleted"] = img_changed
await self._on_event(event, GroupImageChanged)
self._on_event(event, GroupImageChanged)
return
title_changed = parse_system_title_changed(snapshot.text)
if title_changed:
_, event["old_name"] = title_changed
await self._on_event(event, GroupNameChanged)
self._on_event(event, GroupNameChanged)
return
members_changed = parse_system_add_remove(snapshot.text)
if members_changed:
action, event["member"], _ = members_changed
event["member_added"] = action == "added"
await self._on_event(event, MemberListChanged)
self._on_event(event, MemberListChanged)
return
self.logger.warning(
@@ -187,19 +183,20 @@ class Client:
snapshot.text,
)
async def _process_messages(self) -> None:
def _process_messages(self) -> None:
if self._should_process_messages:
for message in await self.account.get_fresh_messages_in_arrival_order():
snapshot = await message.get_snapshot()
await self._on_new_msg(snapshot)
for message in self.account.get_next_messages():
snapshot = message.get_snapshot()
if snapshot.from_id not in [SpecialContactId.SELF, SpecialContactId.DEVICE]:
self._on_new_msg(snapshot)
if snapshot.is_info and snapshot.system_message_type != SystemMessageType.WEBXDC_INFO_MESSAGE:
await self._handle_info_msg(snapshot)
await snapshot.message.mark_seen()
self._handle_info_msg(snapshot)
snapshot.message.mark_seen()
class Bot(Client):
"""Simple bot implementation that listent to events of a single account."""
"""Simple bot implementation that listens to events of a single account."""
async def configure(self, email: str, password: str, **kwargs) -> None:
def configure(self, email: str, password: str, **kwargs) -> None:
kwargs.setdefault("bot", "1")
await super().configure(email, password, **kwargs)
super().configure(email, password, **kwargs)

View File

@@ -31,6 +31,7 @@ class EventType(str, Enum):
SMTP_MESSAGE_SENT = "SmtpMessageSent"
IMAP_MESSAGE_DELETED = "ImapMessageDeleted"
IMAP_MESSAGE_MOVED = "ImapMessageMoved"
IMAP_INBOX_IDLE = "ImapInboxIdle"
NEW_BLOB_FILE = "NewBlobFile"
DELETED_BLOB_FILE = "DeletedBlobFile"
WARNING = "Warning"
@@ -44,6 +45,7 @@ class EventType(str, Enum):
MSG_DELIVERED = "MsgDelivered"
MSG_FAILED = "MsgFailed"
MSG_READ = "MsgRead"
MSG_DELETED = "MsgDeleted"
CHAT_MODIFIED = "ChatModified"
CHAT_EPHEMERAL_TIMER_MODIFIED = "ChatEphemeralTimerModified"
CONTACTS_CHANGED = "ContactsChanged"

View File

@@ -24,39 +24,39 @@ class Contact:
def _rpc(self) -> "Rpc":
return self.account._rpc
async def block(self) -> None:
def block(self) -> None:
"""Block contact."""
await self._rpc.block_contact(self.account.id, self.id)
self._rpc.block_contact(self.account.id, self.id)
async def unblock(self) -> None:
def unblock(self) -> None:
"""Unblock contact."""
await self._rpc.unblock_contact(self.account.id, self.id)
self._rpc.unblock_contact(self.account.id, self.id)
async def delete(self) -> None:
def delete(self) -> None:
"""Delete contact."""
await self._rpc.delete_contact(self.account.id, self.id)
self._rpc.delete_contact(self.account.id, self.id)
async def set_name(self, name: str) -> None:
def set_name(self, name: str) -> None:
"""Change the name of this contact."""
await self._rpc.change_contact_name(self.account.id, self.id, name)
self._rpc.change_contact_name(self.account.id, self.id, name)
async def get_encryption_info(self) -> str:
def get_encryption_info(self) -> str:
"""Get a multi-line encryption info, containing your fingerprint and
the fingerprint of the contact.
"""
return await self._rpc.get_contact_encryption_info(self.account.id, self.id)
return self._rpc.get_contact_encryption_info(self.account.id, self.id)
async def get_snapshot(self) -> AttrDict:
def get_snapshot(self) -> AttrDict:
"""Return a dictionary with a snapshot of all contact properties."""
snapshot = AttrDict(await self._rpc.get_contact(self.account.id, self.id))
snapshot = AttrDict(self._rpc.get_contact(self.account.id, self.id))
snapshot["contact"] = self
return snapshot
async def create_chat(self) -> "Chat":
def create_chat(self) -> "Chat":
"""Create or get an existing 1:1 chat for this contact."""
from .chat import Chat
return Chat(
self.account,
await self._rpc.create_chat_by_contact_id(self.account.id, self.id),
self._rpc.create_chat_by_contact_id(self.account.id, self.id),
)

View File

@@ -16,34 +16,34 @@ class DeltaChat:
def __init__(self, rpc: "Rpc") -> None:
self.rpc = rpc
async def add_account(self) -> Account:
def add_account(self) -> Account:
"""Create a new account database."""
account_id = await self.rpc.add_account()
account_id = self.rpc.add_account()
return Account(self, account_id)
async def get_all_accounts(self) -> List[Account]:
def get_all_accounts(self) -> List[Account]:
"""Return a list of all available accounts."""
account_ids = await self.rpc.get_all_account_ids()
account_ids = self.rpc.get_all_account_ids()
return [Account(self, account_id) for account_id in account_ids]
async def start_io(self) -> None:
def start_io(self) -> None:
"""Start the I/O of all accounts."""
await self.rpc.start_io_for_all_accounts()
self.rpc.start_io_for_all_accounts()
async def stop_io(self) -> None:
def stop_io(self) -> None:
"""Stop the I/O of all accounts."""
await self.rpc.stop_io_for_all_accounts()
self.rpc.stop_io_for_all_accounts()
async def maybe_network(self) -> None:
def maybe_network(self) -> None:
"""Indicate that the network likely has come back or just that the network
conditions might have changed.
"""
await self.rpc.maybe_network()
self.rpc.maybe_network()
async def get_system_info(self) -> AttrDict:
def get_system_info(self) -> AttrDict:
"""Get information about the Delta Chat core in this system."""
return AttrDict(await self.rpc.get_system_info())
return AttrDict(self.rpc.get_system_info())
async def set_translations(self, translations: Dict[str, str]) -> None:
def set_translations(self, translations: Dict[str, str]) -> None:
"""Set stock translation strings."""
await self.rpc.set_stock_strings(translations)
self.rpc.set_stock_strings(translations)

View File

@@ -1,5 +1,4 @@
"""High-level classes for event processing and filtering."""
import inspect
import re
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Callable, Iterable, Iterator, Optional, Set, Tuple, Union
@@ -24,7 +23,7 @@ def _tuple_of(obj, type_: type) -> tuple:
class EventFilter(ABC):
"""The base event filter.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -43,16 +42,13 @@ class EventFilter(ABC):
def __ne__(self, other):
return not self == other
async def _call_func(self, event) -> bool:
def _call_func(self, event) -> bool:
if not self.func:
return True
res = self.func(event)
if inspect.isawaitable(res):
return await res
return res
return self.func(event)
@abstractmethod
async def filter(self, event):
def filter(self, event):
"""Return True-like value if the event passed the filter and should be
used, or False-like value otherwise.
"""
@@ -62,7 +58,7 @@ class RawEvent(EventFilter):
"""Matches raw core events.
:param types: The types of event to match.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -82,10 +78,10 @@ class RawEvent(EventFilter):
return (self.types, self.func) == (other.types, other.func)
return False
async def filter(self, event: "AttrDict") -> bool:
if self.types and event.type not in self.types:
def filter(self, event: "AttrDict") -> bool:
if self.types and event.kind not in self.types:
return False
return await self._call_func(event)
return self._call_func(event)
class NewMessage(EventFilter):
@@ -104,7 +100,7 @@ class NewMessage(EventFilter):
:param is_info: If set to True only match info/system messages, if set to False
only match messages that are not info/system messages. If omitted
info/system messages as well as normal messages will be matched.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -159,7 +155,7 @@ class NewMessage(EventFilter):
)
return False
async def filter(self, event: "AttrDict") -> bool:
def filter(self, event: "AttrDict") -> bool:
if self.is_bot is not None and self.is_bot != event.message_snapshot.is_bot:
return False
if self.is_info is not None and self.is_info != event.message_snapshot.is_info:
@@ -168,11 +164,9 @@ class NewMessage(EventFilter):
return False
if self.pattern:
match = self.pattern(event.message_snapshot.text)
if inspect.isawaitable(match):
match = await match
if not match:
return False
return await super()._call_func(event)
return super()._call_func(event)
class MemberListChanged(EventFilter):
@@ -184,7 +178,7 @@ class MemberListChanged(EventFilter):
:param added: If set to True only match if a member was added, if set to False
only match if a member was removed. If omitted both, member additions
and removals, will be matched.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -201,10 +195,10 @@ class MemberListChanged(EventFilter):
return (self.added, self.func) == (other.added, other.func)
return False
async def filter(self, event: "AttrDict") -> bool:
def filter(self, event: "AttrDict") -> bool:
if self.added is not None and self.added != event.member_added:
return False
return await self._call_func(event)
return self._call_func(event)
class GroupImageChanged(EventFilter):
@@ -216,7 +210,7 @@ class GroupImageChanged(EventFilter):
:param deleted: If set to True only match if the image was deleted, if set to False
only match if a new image was set. If omitted both, image changes and
removals, will be matched.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -233,10 +227,10 @@ class GroupImageChanged(EventFilter):
return (self.deleted, self.func) == (other.deleted, other.func)
return False
async def filter(self, event: "AttrDict") -> bool:
def filter(self, event: "AttrDict") -> bool:
if self.deleted is not None and self.deleted != event.image_deleted:
return False
return await self._call_func(event)
return self._call_func(event)
class GroupNameChanged(EventFilter):
@@ -245,7 +239,7 @@ class GroupNameChanged(EventFilter):
Warning: registering a handler for this event will cause the messages
to be marked as read. Its usage is mainly intended for bots.
:param func: A Callable (async or not) function that should accept the event as input
:param func: A Callable function that should accept the event as input
parameter, and return a bool value indicating whether the event
should be dispatched or not.
"""
@@ -258,8 +252,8 @@ class GroupNameChanged(EventFilter):
return self.func == other.func
return False
async def filter(self, event: "AttrDict") -> bool:
return await self._call_func(event)
def filter(self, event: "AttrDict") -> bool:
return self._call_func(event)
class HookCollection:

View File

@@ -1,6 +1,6 @@
import json
from dataclasses import dataclass
from typing import TYPE_CHECKING, Union
from typing import TYPE_CHECKING, Optional, Union
from ._utils import AttrDict
from .contact import Contact
@@ -21,32 +21,43 @@ class Message:
def _rpc(self) -> "Rpc":
return self.account._rpc
async def send_reaction(self, *reaction: str):
def send_reaction(self, *reaction: str):
"""Send a reaction to this message."""
await self._rpc.send_reaction(self.account.id, self.id, reaction)
self._rpc.send_reaction(self.account.id, self.id, reaction)
async def get_snapshot(self) -> AttrDict:
def get_snapshot(self) -> AttrDict:
"""Get a snapshot with the properties of this message."""
from .chat import Chat
snapshot = AttrDict(await self._rpc.get_message(self.account.id, self.id))
snapshot = AttrDict(self._rpc.get_message(self.account.id, self.id))
snapshot["chat"] = Chat(self.account, snapshot.chat_id)
snapshot["sender"] = Contact(self.account, snapshot.from_id)
snapshot["message"] = self
return snapshot
async def mark_seen(self) -> None:
"""Mark the message as seen."""
await self._rpc.markseen_msgs(self.account.id, [self.id])
def get_reactions(self) -> Optional[AttrDict]:
"""Get message reactions."""
reactions = self._rpc.get_message_reactions(self.account.id, self.id)
if reactions:
return AttrDict(reactions)
return None
async def send_webxdc_status_update(self, update: Union[dict, str], description: str) -> None:
def get_sender_contact(self) -> Contact:
from_id = self.get_snapshot().from_id
return self.account.get_contact_by_id(from_id)
def mark_seen(self) -> None:
"""Mark the message as seen."""
self._rpc.markseen_msgs(self.account.id, [self.id])
def send_webxdc_status_update(self, update: Union[dict, str], description: str) -> None:
"""Send a webxdc status update. This message must be a webxdc."""
if not isinstance(update, str):
update = json.dumps(update)
await self._rpc.send_webxdc_status_update(self.account.id, self.id, update, description)
self._rpc.send_webxdc_status_update(self.account.id, self.id, update, description)
async def get_webxdc_status_updates(self, last_known_serial: int = 0) -> list:
return json.loads(await self._rpc.get_webxdc_status_updates(self.account.id, self.id, last_known_serial))
def get_webxdc_status_updates(self, last_known_serial: int = 0) -> list:
return json.loads(self._rpc.get_webxdc_status_updates(self.account.id, self.id, last_known_serial))
async def get_webxdc_info(self) -> dict:
return await self._rpc.get_webxdc_info(self.account.id, self.id)
def get_webxdc_info(self) -> dict:
return self._rpc.get_webxdc_info(self.account.id, self.id)

View File

@@ -1,66 +1,77 @@
import asyncio
import json
import os
import random
from typing import AsyncGenerator, List, Optional
import aiohttp
import pytest_asyncio
import pytest
from . import Account, AttrDict, Bot, Client, DeltaChat, EventType, Message
from .rpc import Rpc
async def get_temp_credentials() -> dict:
url = os.getenv("DCC_NEW_TMP_EMAIL")
assert url, "Failed to get online account, DCC_NEW_TMP_EMAIL is not set"
# Replace default 5 minute timeout with a 1 minute timeout.
timeout = aiohttp.ClientTimeout(total=60)
async with aiohttp.ClientSession() as session:
async with session.post(url, timeout=timeout) as response:
return json.loads(await response.text())
def get_temp_credentials() -> dict:
domain = os.getenv("CHATMAIL_DOMAIN")
username = "ci-" + "".join(random.choice("2345789acdefghjkmnpqrstuvwxyz") for i in range(6))
password = f"{username}${username}"
addr = f"{username}@{domain}"
return {"email": addr, "password": password}
class ACFactory:
def __init__(self, deltachat: DeltaChat) -> None:
self.deltachat = deltachat
async def get_unconfigured_account(self) -> Account:
return await self.deltachat.add_account()
def get_unconfigured_account(self) -> Account:
account = self.deltachat.add_account()
account.set_config("verified_one_on_one_chats", "1")
return account
async def get_unconfigured_bot(self) -> Bot:
return Bot(await self.get_unconfigured_account())
def get_unconfigured_bot(self) -> Bot:
return Bot(self.get_unconfigured_account())
async def new_preconfigured_account(self) -> Account:
def new_preconfigured_account(self) -> Account:
"""Make a new account with configuration options set, but configuration not started."""
credentials = await get_temp_credentials()
account = await self.get_unconfigured_account()
await account.set_config("addr", credentials["email"])
await account.set_config("mail_pw", credentials["password"])
assert not await account.is_configured()
credentials = get_temp_credentials()
account = self.get_unconfigured_account()
account.set_config("addr", credentials["email"])
account.set_config("mail_pw", credentials["password"])
assert not account.is_configured()
return account
async def new_configured_account(self) -> Account:
account = await self.new_preconfigured_account()
await account.configure()
assert await account.is_configured()
def new_configured_account(self) -> Account:
account = self.new_preconfigured_account()
account.configure()
assert account.is_configured()
return account
async def new_configured_bot(self) -> Bot:
credentials = await get_temp_credentials()
bot = await self.get_unconfigured_bot()
await bot.configure(credentials["email"], credentials["password"])
def new_configured_bot(self) -> Bot:
credentials = get_temp_credentials()
bot = self.get_unconfigured_bot()
bot.configure(credentials["email"], credentials["password"])
return bot
async def get_online_account(self) -> Account:
account = await self.new_configured_account()
await account.start_io()
def get_online_account(self) -> Account:
account = self.new_configured_account()
account.start_io()
while True:
event = account.wait_for_event()
if event.kind == EventType.IMAP_INBOX_IDLE:
break
return account
async def get_online_accounts(self, num: int) -> List[Account]:
return await asyncio.gather(*[self.get_online_account() for _ in range(num)])
def get_online_accounts(self, num: int) -> List[Account]:
return [self.get_online_account() for _ in range(num)]
async def send_message(
def resetup_account(self, ac: Account) -> Account:
"""Resetup account from scratch, losing the encryption key."""
ac.stop_io()
ac_clone = self.get_unconfigured_account()
for i in ["addr", "mail_pw"]:
ac_clone.set_config(i, ac.get_config(i))
ac.remove()
ac_clone.configure()
return ac_clone
def send_message(
self,
to_account: Account,
from_account: Optional[Account] = None,
@@ -69,16 +80,16 @@ class ACFactory:
group: Optional[str] = None,
) -> Message:
if not from_account:
from_account = (await self.get_online_accounts(1))[0]
to_contact = await from_account.create_contact(await to_account.get_config("addr"))
from_account = (self.get_online_accounts(1))[0]
to_contact = from_account.create_contact(to_account.get_config("addr"))
if group:
to_chat = await from_account.create_group(group)
await to_chat.add_contact(to_contact)
to_chat = from_account.create_group(group)
to_chat.add_contact(to_contact)
else:
to_chat = await to_contact.create_chat()
return await to_chat.send_message(text=text, file=file)
to_chat = to_contact.create_chat()
return to_chat.send_message(text=text, file=file)
async def process_message(
def process_message(
self,
to_client: Client,
from_account: Optional[Account] = None,
@@ -86,7 +97,7 @@ class ACFactory:
file: Optional[str] = None,
group: Optional[str] = None,
) -> AttrDict:
await self.send_message(
self.send_message(
to_account=to_client.account,
from_account=from_account,
text=text,
@@ -94,16 +105,16 @@ class ACFactory:
group=group,
)
return await to_client.run_until(lambda e: e.type == EventType.INCOMING_MSG)
return to_client.run_until(lambda e: e.kind == EventType.INCOMING_MSG)
@pytest_asyncio.fixture
async def rpc(tmp_path) -> AsyncGenerator:
@pytest.fixture()
def rpc(tmp_path) -> AsyncGenerator:
rpc_server = Rpc(accounts_dir=str(tmp_path / "accounts"))
async with rpc_server:
with rpc_server:
yield rpc_server
@pytest_asyncio.fixture
async def acfactory(rpc) -> AsyncGenerator:
yield ACFactory(DeltaChat(rpc))
@pytest.fixture()
def acfactory(rpc) -> AsyncGenerator:
return ACFactory(DeltaChat(rpc))

View File

@@ -1,7 +1,12 @@
import asyncio
import itertools
import json
import logging
import os
from typing import Any, Dict, Optional
import subprocess
import sys
from queue import Queue
from threading import Event, Thread
from typing import Any, Dict, Iterator, Optional
class JsonRpcError(Exception):
@@ -10,7 +15,7 @@ class JsonRpcError(Exception):
class Rpc:
def __init__(self, accounts_dir: Optional[str] = None, **kwargs):
"""The given arguments will be passed to asyncio.create_subprocess_exec()"""
"""The given arguments will be passed to subprocess.Popen()"""
if accounts_dir:
kwargs["env"] = {
**kwargs.get("env", os.environ),
@@ -18,81 +23,142 @@ class Rpc:
}
self._kwargs = kwargs
self.process: asyncio.subprocess.Process
self.id: int
self.event_queues: Dict[int, asyncio.Queue]
# Map from request ID to `asyncio.Future` returning the response.
self.request_events: Dict[int, asyncio.Future]
self.reader_task: asyncio.Task
self.process: subprocess.Popen
self.id_iterator: Iterator[int]
self.event_queues: Dict[int, Queue]
# Map from request ID to `threading.Event`.
self.request_events: Dict[int, Event]
# Map from request ID to the result.
self.request_results: Dict[int, Any]
self.request_queue: Queue[Any]
self.closing: bool
self.reader_thread: Thread
self.writer_thread: Thread
self.events_thread: Thread
async def start(self) -> None:
self.process = await asyncio.create_subprocess_exec(
"deltachat-rpc-server",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
**self._kwargs,
)
self.id = 0
def start(self) -> None:
if sys.version_info >= (3, 11):
self.process = subprocess.Popen(
"deltachat-rpc-server",
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
# Prevent subprocess from capturing SIGINT.
process_group=0,
**self._kwargs,
)
else:
self.process = subprocess.Popen(
"deltachat-rpc-server",
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
# `process_group` is not supported before Python 3.11.
preexec_fn=os.setpgrp, # noqa: PLW1509
**self._kwargs,
)
self.id_iterator = itertools.count(start=1)
self.event_queues = {}
self.request_events = {}
self.reader_task = asyncio.create_task(self.reader_loop())
self.request_results = {}
self.request_queue = Queue()
self.closing = False
self.reader_thread = Thread(target=self.reader_loop)
self.reader_thread.start()
self.writer_thread = Thread(target=self.writer_loop)
self.writer_thread.start()
self.events_thread = Thread(target=self.events_loop)
self.events_thread.start()
async def close(self) -> None:
def close(self) -> None:
"""Terminate RPC server process and wait until the reader loop finishes."""
self.process.terminate()
await self.reader_task
self.closing = True
self.stop_io_for_all_accounts()
self.events_thread.join()
self.process.stdin.close()
self.reader_thread.join()
self.request_queue.put(None)
self.writer_thread.join()
async def __aenter__(self):
await self.start()
def __enter__(self):
self.start()
return self
async def __aexit__(self, _exc_type, _exc, _tb):
await self.close()
def __exit__(self, _exc_type, _exc, _tb):
self.close()
async def reader_loop(self) -> None:
while True:
line = await self.process.stdout.readline() # noqa
if not line: # EOF
break
response = json.loads(line)
if "id" in response:
fut = self.request_events.pop(response["id"])
fut.set_result(response)
elif response["method"] == "event":
# An event notification.
params = response["params"]
account_id = params["contextId"]
if account_id not in self.event_queues:
self.event_queues[account_id] = asyncio.Queue()
await self.event_queues[account_id].put(params["event"])
else:
print(response)
def reader_loop(self) -> None:
try:
while True:
line = self.process.stdout.readline()
if not line: # EOF
break
response = json.loads(line)
if "id" in response:
response_id = response["id"]
event = self.request_events.pop(response_id)
self.request_results[response_id] = response
event.set()
else:
logging.warning("Got a response without ID: %s", response)
except Exception:
# Log an exception if the reader loop dies.
logging.exception("Exception in the reader loop")
async def wait_for_event(self, account_id: int) -> Optional[dict]:
def writer_loop(self) -> None:
"""Writer loop ensuring only a single thread writes requests."""
try:
while True:
request = self.request_queue.get()
if not request:
break
data = (json.dumps(request) + "\n").encode()
self.process.stdin.write(data)
self.process.stdin.flush()
except Exception:
# Log an exception if the writer loop dies.
logging.exception("Exception in the writer loop")
def get_queue(self, account_id: int) -> Queue:
if account_id not in self.event_queues:
self.event_queues[account_id] = Queue()
return self.event_queues[account_id]
def events_loop(self) -> None:
"""Requests new events and distributes them between queues."""
try:
while True:
if self.closing:
return
event = self.get_next_event()
account_id = event["contextId"]
queue = self.get_queue(account_id)
event = event["event"]
logging.debug("account_id=%d got an event %s", account_id, event)
queue.put(event)
except Exception:
# Log an exception if the event loop dies.
logging.exception("Exception in the event loop")
def wait_for_event(self, account_id: int) -> Optional[dict]:
"""Waits for the next event from the given account and returns it."""
if account_id in self.event_queues:
return await self.event_queues[account_id].get()
return None
queue = self.get_queue(account_id)
return queue.get()
def __getattr__(self, attr: str):
async def method(*args, **kwargs) -> Any:
self.id += 1
request_id = self.id
assert not (args and kwargs), "Mixing positional and keyword arguments"
def method(*args) -> Any:
request_id = next(self.id_iterator)
request = {
"jsonrpc": "2.0",
"method": attr,
"params": kwargs or args,
"id": self.id,
"params": args,
"id": request_id,
}
data = (json.dumps(request) + "\n").encode()
self.process.stdin.write(data) # noqa
loop = asyncio.get_running_loop()
fut = loop.create_future()
self.request_events[request_id] = fut
response = await fut
event = Event()
self.request_events[request_id] = event
self.request_queue.put(request)
event.wait()
response = self.request_results.pop(request_id)
if "error" in response:
raise JsonRpcError(response["error"])
if "result" in response:

View File

@@ -0,0 +1,552 @@
import logging
from deltachat_rpc_client import Chat, SpecialContactId
def test_qr_setup_contact(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
qr_code, _svg = alice.get_qr_code()
bob.secure_join(qr_code)
alice.wait_for_securejoin_inviter_success()
# Test that Alice verified Bob's profile.
alice_contact_bob = alice.get_contact_by_addr(bob.get_config("addr"))
alice_contact_bob_snapshot = alice_contact_bob.get_snapshot()
assert alice_contact_bob_snapshot.is_verified
bob.wait_for_securejoin_joiner_success()
# Test that Bob verified Alice's profile.
bob_contact_alice = bob.get_contact_by_addr(alice.get_config("addr"))
bob_contact_alice_snapshot = bob_contact_alice.get_snapshot()
assert bob_contact_alice_snapshot.is_verified
def test_qr_securejoin(acfactory):
alice, bob = acfactory.get_online_accounts(2)
logging.info("Alice creates a verified group")
alice_chat = alice.create_group("Verified group", protect=True)
assert alice_chat.get_basic_snapshot().is_protected
logging.info("Bob joins verified group")
qr_code, _svg = alice_chat.get_qr_code()
bob.secure_join(qr_code)
# Check that at least some of the handshake messages are deleted.
for ac in [alice, bob]:
while True:
event = ac.wait_for_event()
if event["kind"] == "ImapMessageDeleted":
break
alice.wait_for_securejoin_inviter_success()
# Test that Alice verified Bob's profile.
alice_contact_bob = alice.get_contact_by_addr(bob.get_config("addr"))
alice_contact_bob_snapshot = alice_contact_bob.get_snapshot()
assert alice_contact_bob_snapshot.is_verified
bob.wait_for_securejoin_joiner_success()
snapshot = bob.get_message_by_id(bob.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Member Me ({}) added by {}.".format(bob.get_config("addr"), alice.get_config("addr"))
assert snapshot.chat.get_basic_snapshot().is_protected
# Test that Bob verified Alice's profile.
bob_contact_alice = bob.get_contact_by_addr(alice.get_config("addr"))
bob_contact_alice_snapshot = bob_contact_alice.get_snapshot()
assert bob_contact_alice_snapshot.is_verified
def test_qr_securejoin_contact_request(acfactory) -> None:
"""Alice invites Bob to a group when Bob's chat with Alice is in a contact request mode."""
alice, bob = acfactory.get_online_accounts(2)
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_text("Hello!")
snapshot = bob.get_message_by_id(bob.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello!"
bob_chat_alice = snapshot.chat
assert bob_chat_alice.get_basic_snapshot().is_contact_request
alice_chat = alice.create_group("Verified group", protect=True)
logging.info("Bob joins verified group")
qr_code, _svg = alice_chat.get_qr_code()
bob.secure_join(qr_code)
while True:
event = bob.wait_for_event()
if event["kind"] == "SecurejoinJoinerProgress" and event["progress"] == 1000:
break
# Chat stays being a contact request.
assert bob_chat_alice.get_basic_snapshot().is_contact_request
def test_qr_readreceipt(acfactory) -> None:
alice, bob, charlie = acfactory.get_online_accounts(3)
logging.info("Bob and Charlie setup contact with Alice")
qr_code, _svg = alice.get_qr_code()
bob.secure_join(qr_code)
charlie.secure_join(qr_code)
for joiner in [bob, charlie]:
joiner.wait_for_securejoin_joiner_success()
logging.info("Alice creates a verified group")
group = alice.create_group("Group", protect=True)
bob_addr = bob.get_config("addr")
charlie_addr = charlie.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_contact_charlie = alice.create_contact(charlie_addr, "Charlie")
group.add_contact(alice_contact_bob)
group.add_contact(alice_contact_charlie)
# Promote a group.
group.send_message(text="Hello")
logging.info("Bob and Charlie receive a group")
bob_msg_id = bob.wait_for_incoming_msg_event().msg_id
bob_message = bob.get_message_by_id(bob_msg_id)
bob_snapshot = bob_message.get_snapshot()
assert bob_snapshot.text == "Hello"
# Charlie receives the same "Hello" message as Bob.
charlie.wait_for_incoming_msg_event()
logging.info("Bob sends a message to the group")
bob_out_message = bob_snapshot.chat.send_message(text="Hi from Bob!")
charlie_msg_id = charlie.wait_for_incoming_msg_event().msg_id
charlie_message = charlie.get_message_by_id(charlie_msg_id)
charlie_snapshot = charlie_message.get_snapshot()
assert charlie_snapshot.text == "Hi from Bob!"
bob_contact_charlie = bob.create_contact(charlie_addr, "Charlie")
assert not bob.get_chat_by_contact(bob_contact_charlie)
logging.info("Charlie reads Bob's message")
charlie_message.mark_seen()
while True:
event = bob.wait_for_event()
if event["kind"] == "MsgRead" and event["msg_id"] == bob_out_message.id:
break
# Receiving a read receipt from Charlie
# should not unblock hidden chat with Charlie for Bob.
assert not bob.get_chat_by_contact(bob_contact_charlie)
def test_verified_group_recovery(acfactory) -> None:
"""Tests verified group recovery by reverifying a member and sending a message in a group."""
ac1, ac2, ac3 = acfactory.get_online_accounts(3)
logging.info("ac1 creates verified group")
chat = ac1.create_group("Verified group", protect=True)
assert chat.get_basic_snapshot().is_protected
logging.info("ac2 joins verified group")
qr_code, _svg = chat.get_qr_code()
ac2.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
# ac1 has ac2 directly verified.
ac1_contact_ac2 = ac1.get_contact_by_addr(ac2.get_config("addr"))
assert ac1_contact_ac2.get_snapshot().verifier_id == SpecialContactId.SELF
logging.info("ac3 joins verified group")
ac3_chat = ac3.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
logging.info("ac2 logs in on a new device")
ac2 = acfactory.resetup_account(ac2)
logging.info("ac2 reverifies with ac3")
qr_code, _svg = ac3.get_qr_code()
ac2.secure_join(qr_code)
ac3.wait_for_securejoin_inviter_success()
logging.info("ac3 sends a message to the group")
assert len(ac3_chat.get_contacts()) == 3
ac3_chat.send_text("Hi!")
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hi!"
msg_id = ac2.wait_for_incoming_msg_event().msg_id
message = ac2.get_message_by_id(msg_id)
snapshot = message.get_snapshot()
assert snapshot.text == "Hi!"
# ac1 contact is verified for ac2 because ac3 gossiped ac1 key in the "Hi!" message.
ac1_contact = ac2.get_contact_by_addr(ac1.get_config("addr"))
assert ac1_contact.get_snapshot().is_verified
# ac2 can write messages to the group.
snapshot.chat.send_text("Works again!")
snapshot = ac3.get_message_by_id(ac3.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Works again!"
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Works again!"
ac1_chat_messages = snapshot.chat.get_messages()
ac2_addr = ac2.get_config("addr")
assert ac1_chat_messages[-2].get_snapshot().text == f"Changed setup for {ac2_addr}"
# ac2 is now verified by ac3 for ac1
ac1_contact_ac3 = ac1.get_contact_by_addr(ac3.get_config("addr"))
assert ac1_contact_ac2.get_snapshot().verifier_id == ac1_contact_ac3.id
def test_verified_group_member_added_recovery(acfactory) -> None:
"""Tests verified group recovery by reverifiying than removing and adding a member back."""
ac1, ac2, ac3 = acfactory.get_online_accounts(3)
logging.info("ac1 creates verified group")
chat = ac1.create_group("Verified group", protect=True)
assert chat.get_basic_snapshot().is_protected
logging.info("ac2 joins verified group")
qr_code, _svg = chat.get_qr_code()
ac2.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
# ac1 has ac2 directly verified.
ac1_contact_ac2 = ac1.get_contact_by_addr(ac2.get_config("addr"))
assert ac1_contact_ac2.get_snapshot().verifier_id == SpecialContactId.SELF
logging.info("ac3 joins verified group")
ac3_chat = ac3.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
logging.info("ac2 logs in on a new device")
ac2 = acfactory.resetup_account(ac2)
logging.info("ac2 reverifies with ac3")
qr_code, _svg = ac3.get_qr_code()
ac2.secure_join(qr_code)
ac3.wait_for_securejoin_inviter_success()
logging.info("ac3 sends a message to the group")
assert len(ac3_chat.get_contacts()) == 3
ac3_chat.send_text("Hi!")
msg_id = ac2.wait_for_incoming_msg_event().msg_id
message = ac2.get_message_by_id(msg_id)
snapshot = message.get_snapshot()
logging.info("Received message %s", snapshot.text)
assert snapshot.text == "Hi!"
ac1.wait_for_incoming_msg_event() # Hi!
ac3_contact_ac2 = ac3.get_contact_by_addr(ac2.get_config("addr"))
ac3_chat.remove_contact(ac3_contact_ac2)
ac3_chat.add_contact(ac3_contact_ac2)
msg_id = ac2.wait_for_incoming_msg_event().msg_id
message = ac2.get_message_by_id(msg_id)
snapshot = message.get_snapshot()
assert "removed" in snapshot.text
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert "removed" in snapshot.text
event = ac2.wait_for_incoming_msg_event()
msg_id = event.msg_id
chat_id = event.chat_id
message = ac2.get_message_by_id(msg_id)
snapshot = message.get_snapshot()
logging.info("ac2 got event message: %s", snapshot.text)
assert "added" in snapshot.text
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert "added" in snapshot.text
chat = Chat(ac2, chat_id)
chat.send_text("Works again!")
msg_id = ac3.wait_for_incoming_msg_event().msg_id
message = ac3.get_message_by_id(msg_id)
snapshot = message.get_snapshot()
assert snapshot.text == "Works again!"
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Works again!"
ac1_contact_ac2 = ac1.get_contact_by_addr(ac2.get_config("addr"))
ac1_contact_ac2_snapshot = ac1_contact_ac2.get_snapshot()
assert ac1_contact_ac2_snapshot.is_verified
assert ac1_contact_ac2_snapshot.verifier_id == ac1.get_contact_by_addr(ac3.get_config("addr")).id
# ac2 is now verified by ac3 for ac1
ac1_contact_ac3 = ac1.get_contact_by_addr(ac3.get_config("addr"))
assert ac1_contact_ac2.get_snapshot().verifier_id == ac1_contact_ac3.id
def test_qr_join_chat_with_pending_bobstate_issue4894(acfactory):
"""Regression test for
issue <https://github.com/deltachat/deltachat-core-rust/issues/4894>.
"""
ac1, ac2, ac3, ac4 = acfactory.get_online_accounts(4)
logging.info("ac3: verify with ac2")
qr_code, _svg = ac2.get_qr_code()
ac3.secure_join(qr_code)
ac2.wait_for_securejoin_inviter_success()
# in order for ac2 to have pending bobstate with a verified group
# we first create a fully joined verified group, and then start
# joining a second time but interrupt it, to create pending bob state
logging.info("ac1: create verified group that ac2 fully joins")
ch1 = ac1.create_group("Group", protect=True)
qr_code, _svg = ch1.get_qr_code()
ac2.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
# ensure ac1 can write and ac2 receives messages in verified chat
ch1.send_text("ac1 says hello")
while 1:
snapshot = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
if snapshot.text == "ac1 says hello":
assert snapshot.chat.get_basic_snapshot().is_protected
break
logging.info("ac1: let ac2 join again but shutoff ac1 in the middle of securejoin")
qr_code, _svg = ch1.get_qr_code()
ac2.secure_join(qr_code)
ac1.remove()
logging.info("ac2 now has pending bobstate but ac1 is shutoff")
# we meanwhile expect ac3/ac2 verification started in the beginning to have completed
assert ac3.get_contact_by_addr(ac2.get_config("addr")).get_snapshot().is_verified
assert ac2.get_contact_by_addr(ac3.get_config("addr")).get_snapshot().is_verified
logging.info("ac3: create a verified group VG with ac2")
vg = ac3.create_group("ac3-created", protect=True)
vg.add_contact(ac3.get_contact_by_addr(ac2.get_config("addr")))
# ensure ac2 receives message in VG
vg.send_text("hello")
while 1:
msg = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
if msg.text == "hello":
assert msg.chat.get_basic_snapshot().is_protected
break
logging.info("ac3: create a join-code for group VG and let ac4 join, check that ac2 got it")
qr_code, _svg = vg.get_qr_code()
ac4.secure_join(qr_code)
ac3.wait_for_securejoin_inviter_success()
while 1:
ev = ac2.wait_for_event()
if "added by unrelated SecureJoin" in str(ev):
return
def test_qr_new_group_unblocked(acfactory):
"""Regression test for a bug introduced in core v1.113.0.
ac2 scans a verified group QR code created by ac1.
This results in creation of a blocked 1:1 chat with ac1 on ac2,
but ac1 contact is not blocked on ac2.
Then ac1 creates a group, adds ac2 there and promotes it by sending a message.
ac2 should receive a message and create a contact request for the group.
Due to a bug previously ac2 created a blocked group.
"""
ac1, ac2 = acfactory.get_online_accounts(2)
ac1_chat = ac1.create_group("Group for joining", protect=True)
qr_code, _svg = ac1_chat.get_qr_code()
ac2.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
ac1_new_chat = ac1.create_group("Another group")
ac1_new_chat.add_contact(ac1.get_contact_by_addr(ac2.get_config("addr")))
# Receive "Member added" message.
ac2.wait_for_incoming_msg_event()
ac1_new_chat.send_text("Hello!")
ac2_msg = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert ac2_msg.text == "Hello!"
assert ac2_msg.chat.get_basic_snapshot().is_contact_request
def test_aeap_flow_verified(acfactory):
"""Test that a new address is added to a contact when it changes its address."""
ac1, ac2, ac1new = acfactory.get_online_accounts(3)
logging.info("ac1: create verified-group QR, ac2 scans and joins")
chat = ac1.create_group("hello", protect=True)
assert chat.get_basic_snapshot().is_protected
qr_code, _svg = chat.get_qr_code()
logging.info("ac2: start QR-code based join-group protocol")
ac2.secure_join(qr_code)
ac1.wait_for_securejoin_inviter_success()
logging.info("sending first message")
msg_out = chat.send_text("old address").get_snapshot()
logging.info("receiving first message")
ac2.wait_for_incoming_msg_event() # member added message
msg_in_1 = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert msg_in_1.text == msg_out.text
logging.info("changing email account")
ac1.set_config("addr", ac1new.get_config("addr"))
ac1.set_config("mail_pw", ac1new.get_config("mail_pw"))
ac1.stop_io()
ac1.configure()
ac1.start_io()
logging.info("sending second message")
msg_out = chat.send_text("changed address").get_snapshot()
logging.info("receiving second message")
msg_in_2 = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id)
msg_in_2_snapshot = msg_in_2.get_snapshot()
assert msg_in_2_snapshot.text == msg_out.text
assert msg_in_2_snapshot.chat.id == msg_in_1.chat.id
assert msg_in_2.get_sender_contact().get_snapshot().address == ac1new.get_config("addr")
assert len(msg_in_2_snapshot.chat.get_contacts()) == 2
assert ac1new.get_config("addr") in [
contact.get_snapshot().address for contact in msg_in_2_snapshot.chat.get_contacts()
]
def test_gossip_verification(acfactory) -> None:
alice, bob, carol = acfactory.get_online_accounts(3)
# Bob verifies Alice.
qr_code, _svg = alice.get_qr_code()
bob.secure_join(qr_code)
bob.wait_for_securejoin_joiner_success()
# Bob verifies Carol.
qr_code, _svg = carol.get_qr_code()
bob.secure_join(qr_code)
bob.wait_for_securejoin_joiner_success()
bob_contact_alice = bob.create_contact(alice.get_config("addr"), "Alice")
bob_contact_carol = bob.create_contact(carol.get_config("addr"), "Carol")
carol_contact_alice = carol.create_contact(alice.get_config("addr"), "Alice")
logging.info("Bob creates an Autocrypt group")
bob_group_chat = bob.create_group("Autocrypt Group")
assert not bob_group_chat.get_basic_snapshot().is_protected
bob_group_chat.add_contact(bob_contact_alice)
bob_group_chat.add_contact(bob_contact_carol)
bob_group_chat.send_message(text="Hello Autocrypt group")
snapshot = carol.get_message_by_id(carol.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello Autocrypt group"
assert snapshot.show_padlock
# Autocrypt group does not propagate verification.
carol_contact_alice_snapshot = carol_contact_alice.get_snapshot()
assert not carol_contact_alice_snapshot.is_verified
logging.info("Bob creates a Securejoin group")
bob_group_chat = bob.create_group("Securejoin Group", protect=True)
assert bob_group_chat.get_basic_snapshot().is_protected
bob_group_chat.add_contact(bob_contact_alice)
bob_group_chat.add_contact(bob_contact_carol)
bob_group_chat.send_message(text="Hello Securejoin group")
snapshot = carol.get_message_by_id(carol.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello Securejoin group"
assert snapshot.show_padlock
# Securejoin propagates verification.
carol_contact_alice_snapshot = carol_contact_alice.get_snapshot()
assert carol_contact_alice_snapshot.is_verified
def test_securejoin_after_contact_resetup(acfactory) -> None:
"""
Regression test for a bug that prevented joining verified group with a QR code
if the group is already created and contains
a contact with inconsistent (Autocrypt and verified keys exist but don't match) key state.
"""
ac1, ac2, ac3 = acfactory.get_online_accounts(3)
# ac3 creates protected group with ac1.
ac3_chat = ac3.create_group("Verified group", protect=True)
# ac1 joins ac3 group.
ac3_qr_code, _svg = ac3_chat.get_qr_code()
ac1.secure_join(ac3_qr_code)
ac1.wait_for_securejoin_joiner_success()
# ac1 waits for member added message and creates a QR code.
snapshot = ac1.get_message_by_id(ac1.wait_for_incoming_msg_event().msg_id).get_snapshot()
ac1_qr_code, _svg = snapshot.chat.get_qr_code()
# ac2 verifies ac1
qr_code, _svg = ac1.get_qr_code()
ac2.secure_join(qr_code)
ac2.wait_for_securejoin_joiner_success()
# ac1 is verified for ac2.
ac2_contact_ac1 = ac2.create_contact(ac1.get_config("addr"), "")
assert ac2_contact_ac1.get_snapshot().is_verified
# ac1 resetups the account.
ac1 = acfactory.resetup_account(ac1)
# ac1 sends a message to ac2.
ac1_contact_ac2 = ac1.create_contact(ac2.get_config("addr"), "")
ac1_chat_ac2 = ac1_contact_ac2.create_chat()
ac1_chat_ac2.send_text("Hello!")
# ac2 receives a message.
snapshot = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello!"
# ac1 is no longer verified for ac2 as new Autocrypt key is not the same as old verified key.
assert not ac2_contact_ac1.get_snapshot().is_verified
# ac1 goes offline.
ac1.remove()
# Scanning a QR code results in creating an unprotected group with an inviter.
# In this case inviter is ac1 which has an inconsistent key state.
# Normally inviter becomes verified as a result of Securejoin protocol
# and then the group chat becomes verified when "Member added" is received,
# but in this case ac1 is offline and this Securejoin process will never finish.
logging.info("ac2 scans ac1 QR code, this is not expected to finish")
ac2.secure_join(ac1_qr_code)
logging.info("ac2 scans ac3 QR code")
ac2.secure_join(ac3_qr_code)
logging.info("ac2 waits for joiner success")
ac2.wait_for_securejoin_joiner_success()
# Wait for member added.
logging.info("ac2 waits for member added message")
snapshot = ac2.get_message_by_id(ac2.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.is_info
ac2_chat = snapshot.chat
assert ac2_chat.get_basic_snapshot().is_protected
assert len(ac2_chat.get_contacts()) == 3
# ac1 is still "not verified" for ac2 due to inconsistent state.
assert not ac2_contact_ac1.get_snapshot().is_verified

View File

@@ -1,4 +1,6 @@
import asyncio
import concurrent.futures
import json
import subprocess
from unittest.mock import MagicMock
import pytest
@@ -6,26 +8,26 @@ from deltachat_rpc_client import EventType, events
from deltachat_rpc_client.rpc import JsonRpcError
@pytest.mark.asyncio()
async def test_system_info(rpc) -> None:
system_info = await rpc.get_system_info()
def test_system_info(rpc) -> None:
system_info = rpc.get_system_info()
assert "arch" in system_info
assert "deltachat_core_version" in system_info
@pytest.mark.asyncio()
async def test_sleep(rpc) -> None:
def test_sleep(rpc) -> None:
"""Test that long-running task does not block short-running task from completion."""
sleep_5_task = asyncio.create_task(rpc.sleep(5.0))
sleep_3_task = asyncio.create_task(rpc.sleep(3.0))
done, pending = await asyncio.wait([sleep_5_task, sleep_3_task], return_when=asyncio.FIRST_COMPLETED)
assert sleep_3_task in done
assert sleep_5_task in pending
sleep_5_task.cancel()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
sleep_5_future = executor.submit(rpc.sleep, 5.0)
sleep_3_future = executor.submit(rpc.sleep, 3.0)
done, pending = concurrent.futures.wait(
[sleep_5_future, sleep_3_future],
return_when=concurrent.futures.FIRST_COMPLETED,
)
assert sleep_3_future in done
assert sleep_5_future in pending
@pytest.mark.asyncio()
async def test_email_address_validity(rpc) -> None:
def test_email_address_validity(rpc) -> None:
valid_addresses = [
"email@example.com",
"36aa165ae3406424e0c61af17700f397cad3fe8ab83d682d0bddf3338a5dd52e@yggmail@yggmail",
@@ -33,17 +35,16 @@ async def test_email_address_validity(rpc) -> None:
invalid_addresses = ["email@", "example.com", "emai221"]
for addr in valid_addresses:
assert await rpc.check_email_validity(addr)
assert rpc.check_email_validity(addr)
for addr in invalid_addresses:
assert not await rpc.check_email_validity(addr)
assert not rpc.check_email_validity(addr)
@pytest.mark.asyncio()
async def test_acfactory(acfactory) -> None:
account = await acfactory.new_configured_account()
def test_acfactory(acfactory) -> None:
account = acfactory.new_configured_account()
while True:
event = await account.wait_for_event()
if event.type == EventType.CONFIGURE_PROGRESS:
event = account.wait_for_event()
if event.kind == EventType.CONFIGURE_PROGRESS:
assert event.progress != 0 # Progress 0 indicates error.
if event.progress == 1000: # Success
break
@@ -52,232 +53,241 @@ async def test_acfactory(acfactory) -> None:
print("Successful configuration")
@pytest.mark.asyncio()
async def test_configure_starttls(acfactory) -> None:
account = await acfactory.new_preconfigured_account()
def test_configure_starttls(acfactory) -> None:
account = acfactory.new_preconfigured_account()
# Use STARTTLS
await account.set_config("mail_security", "2")
await account.set_config("send_security", "2")
await account.configure()
assert await account.is_configured()
account.set_config("mail_security", "2")
account.set_config("send_security", "2")
account.configure()
assert account.is_configured()
@pytest.mark.asyncio()
async def test_account(acfactory) -> None:
alice, bob = await acfactory.get_online_accounts(2)
def test_account(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
alice_chat_bob = await alice_contact_bob.create_chat()
await alice_chat_bob.send_text("Hello!")
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_text("Hello!")
while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
event = bob.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
message = bob.get_message_by_id(msg_id)
snapshot = await message.get_snapshot()
snapshot = message.get_snapshot()
assert snapshot.chat_id == chat_id
assert snapshot.text == "Hello!"
await bob.mark_seen_messages([message])
bob.mark_seen_messages([message])
assert alice != bob
assert repr(alice)
assert (await alice.get_info()).level
assert await alice.get_size()
assert await alice.is_configured()
assert not await alice.get_avatar()
assert await alice.get_contact_by_addr(bob_addr) == alice_contact_bob
assert await alice.get_contacts()
assert await alice.get_contacts(snapshot=True)
assert alice.get_info().level
assert alice.get_size()
assert alice.is_configured()
assert not alice.get_avatar()
assert alice.get_contact_by_addr(bob_addr) == alice_contact_bob
assert alice.get_contacts()
assert alice.get_contacts(snapshot=True)
assert alice.self_contact
assert await alice.get_chatlist()
assert await alice.get_chatlist(snapshot=True)
assert await alice.get_qr_code()
await alice.get_fresh_messages()
await alice.get_fresh_messages_in_arrival_order()
assert alice.get_chatlist()
assert alice.get_chatlist(snapshot=True)
assert alice.get_qr_code()
assert alice.get_fresh_messages()
assert alice.get_next_messages()
group = await alice.create_group("test group")
await group.add_contact(alice_contact_bob)
group_msg = await group.send_message(text="hello")
# Test sending empty message.
assert len(bob.wait_next_messages()) == 0
alice_chat_bob.send_text("")
messages = bob.wait_next_messages()
assert len(messages) == 1
message = messages[0]
snapshot = message.get_snapshot()
assert snapshot.text == ""
bob.mark_seen_messages([message])
group = alice.create_group("test group")
group.add_contact(alice_contact_bob)
group_msg = group.send_message(text="hello")
assert group_msg == alice.get_message_by_id(group_msg.id)
assert group == alice.get_chat_by_id(group.id)
await alice.delete_messages([group_msg])
alice.delete_messages([group_msg])
await alice.set_config("selfstatus", "test")
assert await alice.get_config("selfstatus") == "test"
await alice.update_config(selfstatus="test2")
assert await alice.get_config("selfstatus") == "test2"
alice.set_config("selfstatus", "test")
assert alice.get_config("selfstatus") == "test"
alice.update_config(selfstatus="test2")
assert alice.get_config("selfstatus") == "test2"
assert not await alice.get_blocked_contacts()
await alice_contact_bob.block()
blocked_contacts = await alice.get_blocked_contacts()
assert not alice.get_blocked_contacts()
alice_contact_bob.block()
blocked_contacts = alice.get_blocked_contacts()
assert blocked_contacts
assert blocked_contacts[0].contact == alice_contact_bob
await bob.remove()
await alice.stop_io()
bob.remove()
alice.stop_io()
@pytest.mark.asyncio()
async def test_chat(acfactory) -> None:
alice, bob = await acfactory.get_online_accounts(2)
def test_chat(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
alice_chat_bob = await alice_contact_bob.create_chat()
await alice_chat_bob.send_text("Hello!")
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_text("Hello!")
while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
event = bob.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
message = bob.get_message_by_id(msg_id)
snapshot = await message.get_snapshot()
snapshot = message.get_snapshot()
assert snapshot.chat_id == chat_id
assert snapshot.text == "Hello!"
bob_chat_alice = bob.get_chat_by_id(chat_id)
assert alice_chat_bob != bob_chat_alice
assert repr(alice_chat_bob)
await alice_chat_bob.delete()
await bob_chat_alice.accept()
await bob_chat_alice.block()
bob_chat_alice = await snapshot.sender.create_chat()
await bob_chat_alice.mute()
await bob_chat_alice.unmute()
await bob_chat_alice.pin()
await bob_chat_alice.unpin()
await bob_chat_alice.archive()
await bob_chat_alice.unarchive()
alice_chat_bob.delete()
assert not bob_chat_alice.can_send()
bob_chat_alice.accept()
assert bob_chat_alice.can_send()
bob_chat_alice.block()
bob_chat_alice = snapshot.sender.create_chat()
bob_chat_alice.mute()
bob_chat_alice.unmute()
bob_chat_alice.pin()
bob_chat_alice.unpin()
bob_chat_alice.archive()
bob_chat_alice.unarchive()
with pytest.raises(JsonRpcError): # can't set name for 1:1 chats
await bob_chat_alice.set_name("test")
await bob_chat_alice.set_ephemeral_timer(300)
await bob_chat_alice.get_encryption_info()
bob_chat_alice.set_name("test")
bob_chat_alice.set_ephemeral_timer(300)
bob_chat_alice.get_encryption_info()
group = await alice.create_group("test group")
await group.add_contact(alice_contact_bob)
await group.get_qr_code()
group = alice.create_group("test group")
group.add_contact(alice_contact_bob)
group.get_qr_code()
snapshot = await group.get_basic_snapshot()
snapshot = group.get_basic_snapshot()
assert snapshot.name == "test group"
await group.set_name("new name")
snapshot = await group.get_full_snapshot()
group.set_name("new name")
snapshot = group.get_full_snapshot()
assert snapshot.name == "new name"
msg = await group.send_message(text="hi")
assert (await msg.get_snapshot()).text == "hi"
await group.forward_messages([msg])
msg = group.send_message(text="hi")
assert (msg.get_snapshot()).text == "hi"
group.forward_messages([msg])
await group.set_draft(text="test draft")
draft = await group.get_draft()
group.set_draft(text="test draft")
draft = group.get_draft()
assert draft.text == "test draft"
await group.remove_draft()
assert not await group.get_draft()
group.remove_draft()
assert not group.get_draft()
assert await group.get_messages()
await group.get_fresh_message_count()
await group.mark_noticed()
assert await group.get_contacts()
await group.remove_contact(alice_chat_bob)
await group.get_locations()
assert group.get_messages()
group.get_fresh_message_count()
group.mark_noticed()
assert group.get_contacts()
group.remove_contact(alice_chat_bob)
group.get_locations()
@pytest.mark.asyncio()
async def test_contact(acfactory) -> None:
alice, bob = await acfactory.get_online_accounts(2)
def test_contact(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
assert alice_contact_bob == alice.get_contact_by_id(alice_contact_bob.id)
assert repr(alice_contact_bob)
await alice_contact_bob.block()
await alice_contact_bob.unblock()
await alice_contact_bob.set_name("new name")
await alice_contact_bob.get_encryption_info()
snapshot = await alice_contact_bob.get_snapshot()
alice_contact_bob.block()
alice_contact_bob.unblock()
alice_contact_bob.set_name("new name")
alice_contact_bob.get_encryption_info()
snapshot = alice_contact_bob.get_snapshot()
assert snapshot.address == bob_addr
await alice_contact_bob.create_chat()
alice_contact_bob.create_chat()
@pytest.mark.asyncio()
async def test_message(acfactory) -> None:
alice, bob = await acfactory.get_online_accounts(2)
def test_message(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
alice_chat_bob = await alice_contact_bob.create_chat()
await alice_chat_bob.send_text("Hello!")
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_text("Hello!")
while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
event = bob.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
message = bob.get_message_by_id(msg_id)
snapshot = await message.get_snapshot()
snapshot = message.get_snapshot()
assert snapshot.chat_id == chat_id
assert snapshot.text == "Hello!"
assert not snapshot.is_bot
assert repr(message)
with pytest.raises(JsonRpcError): # chat is not accepted
await snapshot.chat.send_text("hi")
await snapshot.chat.accept()
await snapshot.chat.send_text("hi")
snapshot.chat.send_text("hi")
snapshot.chat.accept()
snapshot.chat.send_text("hi")
await message.mark_seen()
await message.send_reaction("😎")
message.mark_seen()
message.send_reaction("😎")
reactions = message.get_reactions()
assert reactions
snapshot = message.get_snapshot()
assert reactions == snapshot.reactions
@pytest.mark.asyncio()
async def test_is_bot(acfactory) -> None:
def test_is_bot(acfactory) -> None:
"""Test that we can recognize messages submitted by bots."""
alice, bob = await acfactory.get_online_accounts(2)
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
alice_chat_bob = await alice_contact_bob.create_chat()
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
# Alice becomes a bot.
await alice.set_config("bot", "1")
await alice_chat_bob.send_text("Hello!")
alice.set_config("bot", "1")
alice_chat_bob.send_text("Hello!")
while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
event = bob.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
msg_id = event.msg_id
message = bob.get_message_by_id(msg_id)
snapshot = await message.get_snapshot()
snapshot = message.get_snapshot()
assert snapshot.chat_id == event.chat_id
assert snapshot.text == "Hello!"
assert snapshot.is_bot
break
@pytest.mark.asyncio()
async def test_bot(acfactory) -> None:
def test_bot(acfactory) -> None:
mock = MagicMock()
user = (await acfactory.get_online_accounts(1))[0]
bot = await acfactory.new_configured_bot()
bot2 = await acfactory.new_configured_bot()
user = (acfactory.get_online_accounts(1))[0]
bot = acfactory.new_configured_bot()
bot2 = acfactory.new_configured_bot()
assert await bot.is_configured()
assert await bot.account.get_config("bot") == "1"
assert bot.is_configured()
assert bot.account.get_config("bot") == "1"
hook = lambda e: mock.hook(e.msg_id) and None, events.RawEvent(EventType.INCOMING_MSG)
bot.add_hook(*hook)
event = await acfactory.process_message(from_account=user, to_client=bot, text="Hello!")
snapshot = await bot.account.get_message_by_id(event.msg_id).get_snapshot()
event = acfactory.process_message(from_account=user, to_client=bot, text="Hello!")
snapshot = bot.account.get_message_by_id(event.msg_id).get_snapshot()
assert not snapshot.is_bot
mock.hook.assert_called_once_with(event.msg_id)
bot.remove_hook(*hook)
@@ -289,17 +299,106 @@ async def test_bot(acfactory) -> None:
hook = track, events.NewMessage(r"hello")
bot.add_hook(*hook)
bot.add_hook(track, events.NewMessage(command="/help"))
event = await acfactory.process_message(from_account=user, to_client=bot, text="hello")
event = acfactory.process_message(from_account=user, to_client=bot, text="hello")
mock.hook.assert_called_with(event.msg_id)
event = await acfactory.process_message(from_account=user, to_client=bot, text="hello!")
event = acfactory.process_message(from_account=user, to_client=bot, text="hello!")
mock.hook.assert_called_with(event.msg_id)
await acfactory.process_message(from_account=bot2.account, to_client=bot, text="hello")
acfactory.process_message(from_account=bot2.account, to_client=bot, text="hello")
assert len(mock.hook.mock_calls) == 2 # bot messages are ignored between bots
await acfactory.process_message(from_account=user, to_client=bot, text="hey!")
acfactory.process_message(from_account=user, to_client=bot, text="hey!")
assert len(mock.hook.mock_calls) == 2
bot.remove_hook(*hook)
mock.hook.reset_mock()
await acfactory.process_message(from_account=user, to_client=bot, text="hello")
event = await acfactory.process_message(from_account=user, to_client=bot, text="/help")
acfactory.process_message(from_account=user, to_client=bot, text="hello")
event = acfactory.process_message(from_account=user, to_client=bot, text="/help")
mock.hook.assert_called_once_with(event.msg_id)
def test_wait_next_messages(acfactory) -> None:
alice = acfactory.new_configured_account()
# Create a bot account so it does not receive device messages in the beginning.
bot = acfactory.new_preconfigured_account()
bot.set_config("bot", "1")
bot.configure()
# There are no old messages and the call returns immediately.
assert not bot.wait_next_messages()
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
# Bot starts waiting for messages.
next_messages_task = executor.submit(bot.wait_next_messages)
bot_addr = bot.get_config("addr")
alice_contact_bot = alice.create_contact(bot_addr, "Bot")
alice_chat_bot = alice_contact_bot.create_chat()
alice_chat_bot.send_text("Hello!")
next_messages = next_messages_task.result()
assert len(next_messages) == 1
snapshot = next_messages[0].get_snapshot()
assert snapshot.text == "Hello!"
def test_import_export_backup(acfactory, tmp_path) -> None:
alice = acfactory.new_configured_account()
alice.export_backup(tmp_path)
files = list(tmp_path.glob("*.tar"))
alice2 = acfactory.get_unconfigured_account()
alice2.import_backup(files[0])
assert alice2.manager.get_system_info()
def test_import_export_keys(acfactory, tmp_path) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_text("Hello Bob!")
snapshot = bob.get_message_by_id(bob.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello Bob!"
# Alice resetups account, but keeps the key.
alice_keys_path = tmp_path / "alice_keys"
alice_keys_path.mkdir()
alice.export_self_keys(alice_keys_path)
alice = acfactory.resetup_account(alice)
alice.import_self_keys(alice_keys_path)
snapshot.chat.accept()
snapshot.chat.send_text("Hello Alice!")
snapshot = alice.get_message_by_id(alice.wait_for_incoming_msg_event().msg_id).get_snapshot()
assert snapshot.text == "Hello Alice!"
assert snapshot.show_padlock
def test_openrpc_command_line() -> None:
"""Test that "deltachat-rpc-server --openrpc" command returns an OpenRPC specification."""
out = subprocess.run(["deltachat-rpc-server", "--openrpc"], capture_output=True, check=True).stdout
openrpc = json.loads(out)
assert "openrpc" in openrpc
assert "methods" in openrpc
def test_provider_info(rpc) -> None:
account_id = rpc.add_account()
provider_info = rpc.get_provider_info(account_id, "example.org")
assert provider_info["id"] == "example.com"
provider_info = rpc.get_provider_info(account_id, "uep7oiw4ahtaizuloith.org")
assert provider_info is None
# Test MX record resolution.
provider_info = rpc.get_provider_info(account_id, "github.com")
assert provider_info["id"] == "gmail"
# Disable MX record resolution.
rpc.set_config(account_id, "socks5_enabled", "1")
provider_info = rpc.get_provider_info(account_id, "github.com")
assert provider_info is None

View File

@@ -1,24 +1,22 @@
import pytest
from deltachat_rpc_client import EventType
@pytest.mark.asyncio()
async def test_webxdc(acfactory) -> None:
alice, bob = await acfactory.get_online_accounts(2)
def test_webxdc(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = await bob.get_config("addr")
alice_contact_bob = await alice.create_contact(bob_addr, "Bob")
alice_chat_bob = await alice_contact_bob.create_chat()
await alice_chat_bob.send_message(text="Let's play chess!", file="../test-data/webxdc/chess.xdc")
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
alice_chat_bob.send_message(text="Let's play chess!", file="../test-data/webxdc/chess.xdc")
while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
event = bob.wait_for_event()
if event.kind == EventType.INCOMING_MSG:
bob_chat_alice = bob.get_chat_by_id(event.chat_id)
message = bob.get_message_by_id(event.msg_id)
break
webxdc_info = await message.get_webxdc_info()
webxdc_info = message.get_webxdc_info()
assert webxdc_info == {
"document": None,
"icon": "icon.png",
@@ -28,20 +26,32 @@ async def test_webxdc(acfactory) -> None:
"summary": None,
}
status_updates = await message.get_webxdc_status_updates()
status_updates = message.get_webxdc_status_updates()
assert status_updates == []
await bob_chat_alice.accept()
await message.send_webxdc_status_update({"payload": 42}, "")
await message.send_webxdc_status_update({"payload": "Second update"}, "description")
bob_chat_alice.accept()
message.send_webxdc_status_update({"payload": 42}, "")
message.send_webxdc_status_update({"payload": "Second update"}, "description")
status_updates = await message.get_webxdc_status_updates()
status_updates = message.get_webxdc_status_updates()
assert status_updates == [
{"payload": 42, "serial": 1, "max_serial": 2},
{"payload": "Second update", "serial": 2, "max_serial": 2},
]
status_updates = await message.get_webxdc_status_updates(1)
status_updates = message.get_webxdc_status_updates(1)
assert status_updates == [
{"payload": "Second update", "serial": 2, "max_serial": 2},
]
def test_webxdc_insert_lots_of_updates(acfactory) -> None:
alice, bob = acfactory.get_online_accounts(2)
bob_addr = bob.get_config("addr")
alice_contact_bob = alice.create_contact(bob_addr, "Bob")
alice_chat_bob = alice_contact_bob.create_chat()
message = alice_chat_bob.send_message(text="Let's play chess!", file="../test-data/webxdc/chess.xdc")
for i in range(2000):
message.send_webxdc_status_update({"payload": str(i)}, "description")

View File

@@ -6,17 +6,16 @@ envlist =
[testenv]
commands =
pytest {posargs}
pytest -n6 {posargs}
setenv =
# Avoid stack overflow when Rust core is built without optimizations.
RUST_MIN_STACK=8388608
passenv =
DCC_NEW_TMP_EMAIL
CHATMAIL_DOMAIN
deps =
pytest
pytest-asyncio
aiohttp
aiodns
pytest-timeout
pytest-xdist
[testenv:lint]
skipsdist = True
@@ -27,3 +26,8 @@ deps =
commands =
black --quiet --check --diff src/ examples/ tests/
ruff src/ examples/ tests/
[pytest]
timeout = 300
log_cli = true
log_level = debug

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat-rpc-server"
version = "1.111.0"
version = "1.132.1"
description = "DeltaChat JSON-RPC server"
edition = "2021"
readme = "README.md"
@@ -9,20 +9,19 @@ license = "MPL-2.0"
keywords = ["deltachat", "chat", "openpgp", "email", "encryption"]
categories = ["cryptography", "std", "email"]
[[bin]]
name = "deltachat-rpc-server"
[dependencies]
deltachat-jsonrpc = { path = "../deltachat-jsonrpc", default-features = false }
deltachat = { path = "..", default-features = false }
anyhow = "1"
env_logger = { version = "0.10.0" }
futures-lite = "1.12.0"
futures-lite = "2.0.0"
log = "0.4"
serde_json = "1.0.91"
serde_json = "1.0.105"
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.25.0", features = ["io-std"] }
yerpc = { version = "0.4.0", features = ["anyhow_expose"] }
tokio = { version = "1.33.0", features = ["io-std"] }
tokio-util = "0.7.9"
yerpc = { version = "0.5.2", features = ["anyhow_expose", "openrpc"] }
[features]
default = ["vendored"]

View File

@@ -32,3 +32,6 @@ languages other than Rust, for example:
1. Python: https://github.com/deltachat/deltachat-core-rust/tree/master/deltachat-rpc-client/
2. Go: https://github.com/deltachat/deltachat-rpc-client-go/
Run `deltachat-rpc-server --version` to check the version of the server.
Run `deltachat-rpc-server --openrpc` to get [OpenRPC](https://open-rpc.org/) specification of the provided JSON-RPC API.

View File

@@ -1,71 +0,0 @@
///! Delta Chat core RPC server.
///!
///! It speaks JSON Lines over stdio.
use std::path::PathBuf;
use anyhow::Result;
use deltachat_jsonrpc::api::events::event_to_json_rpc_notification;
use deltachat_jsonrpc::api::{Accounts, CommandApi};
use futures_lite::stream::StreamExt;
use tokio::io::{self, AsyncBufReadExt, BufReader};
use tokio::task::JoinHandle;
use yerpc::{RpcClient, RpcSession};
#[tokio::main(flavor = "multi_thread")]
async fn main() -> Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let path = std::env::var("DC_ACCOUNTS_PATH").unwrap_or_else(|_| "accounts".to_string());
log::info!("Starting with accounts directory `{}`.", path);
let accounts = Accounts::new(PathBuf::from(&path)).await?;
let events = accounts.get_event_emitter();
log::info!("Creating JSON-RPC API.");
let state = CommandApi::new(accounts);
let (client, mut out_receiver) = RpcClient::new();
let session = RpcSession::new(client.clone(), state);
// Events task converts core events to JSON-RPC notifications.
let events_task: JoinHandle<Result<()>> = tokio::spawn(async move {
while let Some(event) = events.recv().await {
let event = event_to_json_rpc_notification(event);
client.send_notification("event", Some(event)).await?;
}
Ok(())
});
// Send task prints JSON responses to stdout.
let send_task: JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
while let Some(message) = out_receiver.next().await {
let message = serde_json::to_string(&message)?;
log::trace!("RPC send {}", message);
println!("{message}");
}
Ok(())
});
// Receiver task reads JSON requests from stdin.
let recv_task: JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
let stdin = io::stdin();
let mut lines = BufReader::new(stdin).lines();
while let Some(message) = lines.next_line().await? {
log::trace!("RPC recv {}", message);
let session = session.clone();
tokio::spawn(async move {
session.handle_incoming(&message).await;
});
}
log::info!("EOF reached on stdin");
Ok(())
});
// Wait for the end of stdin.
recv_task.await??;
// Shutdown the server.
send_task.abort();
events_task.abort();
Ok(())
}

View File

@@ -0,0 +1,151 @@
//! Delta Chat core RPC server.
//!
//! It speaks JSON Lines over stdio.
use std::env;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{anyhow, Context as _, Result};
use deltachat::constants::DC_VERSION_STR;
use deltachat_jsonrpc::api::{Accounts, CommandApi};
use futures_lite::stream::StreamExt;
use tokio::io::{self, AsyncBufReadExt, BufReader};
use yerpc::RpcServer as _;
#[cfg(target_family = "unix")]
use tokio::signal::unix as signal_unix;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use yerpc::{RpcClient, RpcSession};
#[tokio::main(flavor = "multi_thread")]
async fn main() {
let r = main_impl().await;
// From tokio documentation:
// "For technical reasons, stdin is implemented by using an ordinary blocking read on a separate
// thread, and it is impossible to cancel that read. This can make shutdown of the runtime hang
// until the user presses enter."
std::process::exit(if r.is_ok() { 0 } else { 1 });
}
async fn main_impl() -> Result<()> {
let mut args = env::args_os();
let _program_name = args.next().context("no command line arguments found")?;
if let Some(first_arg) = args.next() {
if first_arg.to_str() == Some("--version") {
if let Some(arg) = args.next() {
return Err(anyhow!("Unrecognized argument {:?}", arg));
}
eprintln!("{}", &*DC_VERSION_STR);
return Ok(());
} else if first_arg.to_str() == Some("--openrpc") {
if let Some(arg) = args.next() {
return Err(anyhow!("Unrecognized argument {:?}", arg));
}
println!("{}", CommandApi::openrpc_specification()?);
return Ok(());
} else {
return Err(anyhow!("Unrecognized option {:?}", first_arg));
}
}
if let Some(arg) = args.next() {
return Err(anyhow!("Unrecognized argument {:?}", arg));
}
// Install signal handlers early so that the shutdown is graceful starting from here.
let _ctrl_c = tokio::signal::ctrl_c();
#[cfg(target_family = "unix")]
let mut sigterm = signal_unix::signal(signal_unix::SignalKind::terminate())?;
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let path = std::env::var("DC_ACCOUNTS_PATH").unwrap_or_else(|_| "accounts".to_string());
log::info!("Starting with accounts directory `{}`.", path);
let writable = true;
let accounts = Accounts::new(PathBuf::from(&path), writable).await?;
log::info!("Creating JSON-RPC API.");
let accounts = Arc::new(RwLock::new(accounts));
let state = CommandApi::from_arc(accounts.clone());
let (client, mut out_receiver) = RpcClient::new();
let session = RpcSession::new(client.clone(), state.clone());
let main_cancel = CancellationToken::new();
// Send task prints JSON responses to stdout.
let cancel = main_cancel.clone();
let send_task: JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
let _cancel_guard = cancel.clone().drop_guard();
loop {
let message = tokio::select! {
_ = cancel.cancelled() => break,
message = out_receiver.next() => match message {
None => break,
Some(message) => serde_json::to_string(&message)?,
}
};
log::trace!("RPC send {}", message);
println!("{message}");
}
Ok(())
});
let cancel = main_cancel.clone();
let sigterm_task: JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
#[cfg(target_family = "unix")]
{
let _cancel_guard = cancel.clone().drop_guard();
tokio::select! {
_ = cancel.cancelled() => (),
_ = sigterm.recv() => {
log::info!("got SIGTERM");
}
}
}
let _ = cancel;
Ok(())
});
// Receiver task reads JSON requests from stdin.
let cancel = main_cancel.clone();
let recv_task: JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
let _cancel_guard = cancel.clone().drop_guard();
let stdin = io::stdin();
let mut lines = BufReader::new(stdin).lines();
loop {
let message = tokio::select! {
_ = cancel.cancelled() => break,
_ = tokio::signal::ctrl_c() => {
log::info!("got ctrl-c event");
break;
}
message = lines.next_line() => match message? {
None => {
log::info!("EOF reached on stdin");
break;
}
Some(message) => message,
}
};
log::trace!("RPC recv {}", message);
let session = session.clone();
tokio::spawn(async move {
session.handle_incoming(&message).await;
});
}
Ok(())
});
main_cancel.cancelled().await;
accounts.read().await.stop_io().await;
drop(accounts);
drop(state);
send_task.await??;
sigterm_task.await??;
recv_task.await??;
Ok(())
}

View File

@@ -8,5 +8,5 @@ license = "MPL-2.0"
proc-macro = true
[dependencies]
syn = "1"
syn = "2"
quote = "1"

View File

@@ -2,51 +2,74 @@
unmaintained = "allow"
ignore = [
"RUSTSEC-2020-0071",
"RUSTSEC-2022-0093",
# Only affects windows if using non-default allocator (and unmaintained).
"RUSTSEC-2021-0145",
# Timing attack on RSA.
# Delta Chat does not use RSA for new keys
# and this requires precise measurement of the decryption time by the attacker.
# There is no fix at the time of writing this (2023-11-28).
# <https://rustsec.org/advisories/RUSTSEC-2023-0071>
"RUSTSEC-2023-0071",
]
[bans]
# Accept some duplicate versions, ideally we work towards this list
# becoming empty. Adding versions forces us to revisit this at least
# when upgrading.
# Please keep this list alphabetically sorted.
skip = [
{ name = "async-channel", version = "1.9.0" },
{ name = "base16ct", version = "0.1.1" },
{ name = "base64", version = "<0.21" },
{ name = "bitflags", version = "1.3.2" },
{ name = "block-buffer", version = "<0.10" },
{ name = "darling", version = "<0.14" },
{ name = "convert_case", version = "0.4.0" },
{ name = "curve25519-dalek", version = "3.2.0" },
{ name = "darling_core", version = "<0.14" },
{ name = "darling_macro", version = "<0.14" },
{ name = "darling", version = "<0.14" },
{ name = "der", version = "0.6.1" },
{ name = "digest", version = "<0.10" },
{ name = "env_logger", version = "<0.10" },
{ name = "ed25519-dalek", version = "1.0.1" },
{ name = "ed25519", version = "1.5.3" },
{ name = "event-listener", version = "2.5.3" },
{ name = "fd-lock", version = "3.0.13" },
{ name = "getrandom", version = "<0.2" },
{ name = "hermit-abi", version = "<0.3" },
{ name = "humantime", version = "<2.1" },
{ name = "idna", version = "<0.3" },
{ name = "nom", version = "<7.1" },
{ name = "h2", version = "0.3.22" },
{ name = "http-body", version = "0.4.5" },
{ name = "http", version = "0.2.11" },
{ name = "hyper", version = "0.14.27" },
{ name = "idna", version = "0.4.0" },
{ name = "pem-rfc7468", version = "0.6.0" },
{ name = "pkcs8", version = "0.9.0" },
{ name = "quick-error", version = "<2.0" },
{ name = "rand", version = "<0.8" },
{ name = "rand_chacha", version = "<0.3" },
{ name = "rand_core", version = "<0.6" },
{ name = "rand", version = "<0.8" },
{ name = "redox_syscall", version = "0.3.5" },
{ name = "regex-automata", version = "0.1.10" },
{ name = "regex-syntax", version = "0.6.29" },
{ name = "ring", version = "0.16.20" },
{ name = "sec1", version = "0.3.0" },
{ name = "sha2", version = "<0.10" },
{ name = "time", version = "<0.3" },
{ name = "version_check", version = "<0.9" },
{ name = "wasi", version = "<0.11" },
{ name = "windows-sys", version = "<0.45" },
{ name = "windows_x86_64_msvc", version = "<0.42" },
{ name = "windows_x86_64_gnu", version = "<0.42" },
{ name = "windows_i686_msvc", version = "<0.42" },
{ name = "windows_i686_gnu", version = "<0.42" },
{ name = "windows_aarch64_msvc", version = "<0.42" },
{ name = "unicode-xid", version = "<0.2.4" },
{ name = "syn", version = "<1.0" },
{ name = "quote", version = "<1.0" },
{ name = "proc-macro2", version = "<1.0" },
{ name = "portable-atomic", version = "<1.0" },
{ name = "signature", version = "1.6.4" },
{ name = "socket2", version = "0.4.9" },
{ name = "spin", version = "<0.9.6" },
{ name = "convert_case", version = "0.4.0" },
{ name = "clap_lex", version = "0.2.4" },
{ name = "clap", version = "3.2.23" },
{ name = "spki", version = "0.6.0" },
{ name = "syn", version = "1.0.109" },
{ name = "time", version = "<0.3" },
{ name = "untrusted", version = "0.7.1" },
{ name = "wasi", version = "<0.11" },
{ name = "windows_aarch64_gnullvm", version = "<0.52" },
{ name = "windows_aarch64_msvc", version = "<0.52" },
{ name = "windows_i686_gnu", version = "<0.52" },
{ name = "windows_i686_msvc", version = "<0.52" },
{ name = "windows-sys", version = "<0.52" },
{ name = "windows-targets", version = "<0.52" },
{ name = "windows", version = "0.32.0" },
{ name = "windows_x86_64_gnullvm", version = "<0.52" },
{ name = "windows_x86_64_gnu", version = "<0.52" },
{ name = "windows_x86_64_msvc", version = "<0.52" },
]
@@ -78,7 +101,6 @@ license-files = [
github = [
"async-email",
"deltachat",
"n0-computer",
"quinn-rs",
"dignifiedquire",
"djc",
"n0-computer", # iroh
]

View File

@@ -57,7 +57,7 @@ Note that usually a mail is signed by a key that has a UID matching the from add
### Notes:
- We treat protected and non-protected chats the same
- We leave the aeap transition statement away since it seems not to be needed, makes things harder on the sending side, wastes some network traffic, and is worse for privacy (since more pepole know what old addresses you had).
- We leave the aeap transition statement away since it seems not to be needed, makes things harder on the sending side, wastes some network traffic, and is worse for privacy (since more people know what old addresses you had).
- As soon as we encrypt read receipts, sending a read receipt will be enough to tell a lot of people that you transitioned
- AEAP will make the problem of inconsistent group state worse, both because it doesn't work if the message is unencrypted (even if the design allowed it, it would be problematic security-wise) and because some chat partners may have gotten the transition and some not. We should do something against this at some point in the future, like asking the user whether they want to add/remove the members to restore consistent group state.
@@ -108,7 +108,7 @@ The most obvious alternative would be to create a new contact with the new addre
#### Upsides:
- With this approach, it's easier to switch to a model where the info about the transition is encoded in the PGP key. Since the key is gossiped, the information about the transition will spread virally.
- (Also, less important: Slightly faster transition: If you send a message to e.g. "Delta Chat Dev", all members of the "sub-group" "delta android" will know of your transition.)
- It's easier to implement (if too many problems turn up, we can still switch to another approach and didn't wast that much development time.)
- It's easier to implement (if too many problems turn up, we can still switch to another approach and didn't waste that much development time.)
[full messages](https://github.com/deltachat/deltachat-core-rust/pull/2896#discussion_r852002161)

View File

@@ -1,100 +0,0 @@
use deltachat::chat::{self, ChatId};
use deltachat::chatlist::*;
use deltachat::config;
use deltachat::contact::*;
use deltachat::context::*;
use deltachat::message::Message;
use deltachat::stock_str::StockStrings;
use deltachat::{EventType, Events};
use tempfile::tempdir;
fn cb(event: EventType) {
match event {
EventType::ConfigureProgress { progress, .. } => {
log::info!("progress: {}", progress);
}
EventType::Info(msg) => {
log::info!("{}", msg);
}
EventType::Warning(msg) => {
log::warn!("{}", msg);
}
EventType::Error(msg) => {
log::error!("{}", msg);
}
event => {
log::info!("{:?}", event);
}
}
}
/// Run with `RUST_LOG=simple=info cargo run --release --example simple -- email pw`.
#[tokio::main]
async fn main() {
pretty_env_logger::try_init_timed().ok();
let dir = tempdir().unwrap();
let dbfile = dir.path().join("db.sqlite");
log::info!("creating database {:?}", dbfile);
let ctx = Context::new(&dbfile, 0, Events::new(), StockStrings::new())
.await
.expect("Failed to create context");
let info = ctx.get_info().await;
log::info!("info: {:#?}", info);
let events = ctx.get_event_emitter();
let events_spawn = tokio::task::spawn(async move {
while let Some(event) = events.recv().await {
cb(event.typ);
}
});
log::info!("configuring");
let args = std::env::args().collect::<Vec<String>>();
assert_eq!(args.len(), 3, "requires email password");
let email = args[1].clone();
let pw = args[2].clone();
ctx.set_config(config::Config::Addr, Some(&email))
.await
.unwrap();
ctx.set_config(config::Config::MailPw, Some(&pw))
.await
.unwrap();
ctx.configure().await.unwrap();
log::info!("------ RUN ------");
ctx.start_io().await;
log::info!("--- SENDING A MESSAGE ---");
let contact_id = Contact::create(&ctx, "dignifiedquire", "dignifiedquire@gmail.com")
.await
.unwrap();
let chat_id = ChatId::create_for_contact(&ctx, contact_id).await.unwrap();
for i in 0..1 {
log::info!("sending message {}", i);
chat::send_text_msg(&ctx, chat_id, format!("Hi, here is my {i}nth message!"))
.await
.unwrap();
}
// wait for the message to be sent out
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
log::info!("fetching chats..");
let chats = Chatlist::try_load(&ctx, 0, None, None).await.unwrap();
for i in 0..chats.len() {
let msg = Message::load_from_db(&ctx, chats.get_msg_id(i).unwrap().unwrap())
.await
.unwrap();
log::info!("[{}] msg: {:?}", i, msg);
}
log::info!("stopping");
ctx.stop_io().await;
log::info!("closing");
drop(ctx);
events_spawn.await.unwrap();
}

2465
fuzz/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -40,7 +40,7 @@ npm install deltachat-node
## Dependencies
- Nodejs >= `v16.0.0`
- Nodejs >= `v18.0.0`
- rustup (optional if you can't use the prebuilds)
> On Windows, you may need to also install **Perl** to be able to compile deltachat-core.
@@ -113,8 +113,8 @@ Then, in the `deltachat-desktop` repository, run:
deltachat doesn't support universal (fat) binaries (that contain builds for both cpu architectures) yet, until it does you can use the following workaround to get x86_64 builds:
```
$ fnm install 17 --arch x64
$ fnm use 17
$ fnm install 19 --arch x64
$ fnm use 19
$ node -p process.arch
# result should be x64
$ rustup target add x86_64-apple-darwin
@@ -127,8 +127,8 @@ $ npm run test
If your node and electron are already build for arm64 you can also try building for arm:
```
$ fnm install 16 --arch arm64
$ fnm use 16
$ fnm install 18 --arch arm64
$ fnm use 18
$ node -p process.arch
# result should be arm64
$ npm_config_arch=arm64 npm run build
@@ -204,10 +204,10 @@ Running `npm test` ends with showing a code coverage report, which is produced b
The coverage report from `nyc` in the console is rather limited. To get a more detailed coverage report you can run `npm run coverage-html-report`. This will produce a html report from the `nyc` data and display it in a browser on your local machine.
To run the integration tests you need to set the `DCC_NEW_TMP_EMAIL` environment variables. E.g.:
To run the integration tests you need to set the `CHATMAIL_DOMAIN` environment variables. E.g.:
```
$ export DCC_NEW_TMP_EMAIL=https://testrun.org/new_email?t=[token]
$ export CHATMAIL_DOMAIN=chat.example.org
$ npm run test
```

View File

@@ -28,6 +28,7 @@ module.exports = {
DC_DOWNLOAD_DONE: 0,
DC_DOWNLOAD_FAILURE: 20,
DC_DOWNLOAD_IN_PROGRESS: 1000,
DC_DOWNLOAD_UNDECIPHERABLE: 30,
DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED: 2021,
DC_EVENT_CHAT_MODIFIED: 2020,
DC_EVENT_CONFIGURE_PROGRESS: 2041,
@@ -37,6 +38,7 @@ module.exports = {
DC_EVENT_ERROR: 400,
DC_EVENT_ERROR_SELF_NOT_IN_GROUP: 410,
DC_EVENT_IMAP_CONNECTED: 102,
DC_EVENT_IMAP_INBOX_IDLE: 106,
DC_EVENT_IMAP_MESSAGE_DELETED: 104,
DC_EVENT_IMAP_MESSAGE_MOVED: 105,
DC_EVENT_IMEX_FILE_WRITTEN: 2052,
@@ -47,6 +49,7 @@ module.exports = {
DC_EVENT_LOCATION_CHANGED: 2035,
DC_EVENT_MSGS_CHANGED: 2000,
DC_EVENT_MSGS_NOTICED: 2008,
DC_EVENT_MSG_DELETED: 2016,
DC_EVENT_MSG_DELIVERED: 2010,
DC_EVENT_MSG_FAILED: 2012,
DC_EVENT_MSG_READ: 2015,
@@ -88,6 +91,7 @@ module.exports = {
DC_KEY_GEN_DEFAULT: 0,
DC_KEY_GEN_ED25519: 2,
DC_KEY_GEN_RSA2048: 1,
DC_KEY_GEN_RSA4096: 3,
DC_LP_AUTH_NORMAL: 4,
DC_LP_AUTH_OAUTH2: 2,
DC_MEDIA_QUALITY_BALANCED: 0,
@@ -112,6 +116,7 @@ module.exports = {
DC_QR_ADDR: 320,
DC_QR_ASK_VERIFYCONTACT: 200,
DC_QR_ASK_VERIFYGROUP: 202,
DC_QR_BACKUP: 251,
DC_QR_ERROR: 400,
DC_QR_FPR_MISMATCH: 220,
DC_QR_FPR_OK: 210,
@@ -149,10 +154,14 @@ module.exports = {
DC_STR_AEAP_EXPLANATION_AND_LINK: 123,
DC_STR_ARCHIVEDCHATS: 40,
DC_STR_AUDIO: 11,
DC_STR_BACKUP_TRANSFER_MSG_BODY: 163,
DC_STR_BACKUP_TRANSFER_QR: 162,
DC_STR_BAD_TIME_MSG_BODY: 85,
DC_STR_BROADCAST_LIST: 115,
DC_STR_CANNOT_LOGIN: 60,
DC_STR_CANTDECRYPT_MSG_BODY: 29,
DC_STR_CHAT_PROTECTION_DISABLED: 171,
DC_STR_CHAT_PROTECTION_ENABLED: 170,
DC_STR_CONFIGURATION_FAILED: 84,
DC_STR_CONNECTED: 107,
DC_STR_CONNTECTING: 108,
@@ -231,6 +240,7 @@ module.exports = {
DC_STR_MSGGRPNAME: 15,
DC_STR_MSGLOCATIONDISABLED: 65,
DC_STR_MSGLOCATIONENABLED: 64,
DC_STR_NEW_GROUP_SEND_FIRST_MESSAGE: 172,
DC_STR_NOMESSAGES: 1,
DC_STR_NOT_CONNECTED: 121,
DC_STR_NOT_SUPPORTED_BY_PROVIDER: 113,
@@ -238,12 +248,6 @@ module.exports = {
DC_STR_OUTGOING_MESSAGES: 104,
DC_STR_PARTIAL_DOWNLOAD_MSG_BODY: 99,
DC_STR_PART_OF_TOTAL_USED: 116,
DC_STR_PROTECTION_DISABLED: 89,
DC_STR_PROTECTION_DISABLED_BY_OTHER: 161,
DC_STR_PROTECTION_DISABLED_BY_YOU: 160,
DC_STR_PROTECTION_ENABLED: 88,
DC_STR_PROTECTION_ENABLED_BY_OTHER: 159,
DC_STR_PROTECTION_ENABLED_BY_YOU: 158,
DC_STR_QUOTA_EXCEEDING_MSG_BODY: 98,
DC_STR_READRCPT: 31,
DC_STR_READRCPT_MAILBODY: 32,

View File

@@ -8,6 +8,7 @@ module.exports = {
103: 'DC_EVENT_SMTP_MESSAGE_SENT',
104: 'DC_EVENT_IMAP_MESSAGE_DELETED',
105: 'DC_EVENT_IMAP_MESSAGE_MOVED',
106: 'DC_EVENT_IMAP_INBOX_IDLE',
150: 'DC_EVENT_NEW_BLOB_FILE',
151: 'DC_EVENT_DELETED_BLOB_FILE',
300: 'DC_EVENT_WARNING',
@@ -21,6 +22,7 @@ module.exports = {
2010: 'DC_EVENT_MSG_DELIVERED',
2012: 'DC_EVENT_MSG_FAILED',
2015: 'DC_EVENT_MSG_READ',
2016: 'DC_EVENT_MSG_DELETED',
2020: 'DC_EVENT_CHAT_MODIFIED',
2021: 'DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED',
2030: 'DC_EVENT_CONTACTS_CHANGED',

View File

@@ -28,6 +28,7 @@ export enum C {
DC_DOWNLOAD_DONE = 0,
DC_DOWNLOAD_FAILURE = 20,
DC_DOWNLOAD_IN_PROGRESS = 1000,
DC_DOWNLOAD_UNDECIPHERABLE = 30,
DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED = 2021,
DC_EVENT_CHAT_MODIFIED = 2020,
DC_EVENT_CONFIGURE_PROGRESS = 2041,
@@ -37,6 +38,7 @@ export enum C {
DC_EVENT_ERROR = 400,
DC_EVENT_ERROR_SELF_NOT_IN_GROUP = 410,
DC_EVENT_IMAP_CONNECTED = 102,
DC_EVENT_IMAP_INBOX_IDLE = 106,
DC_EVENT_IMAP_MESSAGE_DELETED = 104,
DC_EVENT_IMAP_MESSAGE_MOVED = 105,
DC_EVENT_IMEX_FILE_WRITTEN = 2052,
@@ -47,6 +49,7 @@ export enum C {
DC_EVENT_LOCATION_CHANGED = 2035,
DC_EVENT_MSGS_CHANGED = 2000,
DC_EVENT_MSGS_NOTICED = 2008,
DC_EVENT_MSG_DELETED = 2016,
DC_EVENT_MSG_DELIVERED = 2010,
DC_EVENT_MSG_FAILED = 2012,
DC_EVENT_MSG_READ = 2015,
@@ -88,6 +91,7 @@ export enum C {
DC_KEY_GEN_DEFAULT = 0,
DC_KEY_GEN_ED25519 = 2,
DC_KEY_GEN_RSA2048 = 1,
DC_KEY_GEN_RSA4096 = 3,
DC_LP_AUTH_NORMAL = 4,
DC_LP_AUTH_OAUTH2 = 2,
DC_MEDIA_QUALITY_BALANCED = 0,
@@ -112,6 +116,7 @@ export enum C {
DC_QR_ADDR = 320,
DC_QR_ASK_VERIFYCONTACT = 200,
DC_QR_ASK_VERIFYGROUP = 202,
DC_QR_BACKUP = 251,
DC_QR_ERROR = 400,
DC_QR_FPR_MISMATCH = 220,
DC_QR_FPR_OK = 210,
@@ -149,10 +154,14 @@ export enum C {
DC_STR_AEAP_EXPLANATION_AND_LINK = 123,
DC_STR_ARCHIVEDCHATS = 40,
DC_STR_AUDIO = 11,
DC_STR_BACKUP_TRANSFER_MSG_BODY = 163,
DC_STR_BACKUP_TRANSFER_QR = 162,
DC_STR_BAD_TIME_MSG_BODY = 85,
DC_STR_BROADCAST_LIST = 115,
DC_STR_CANNOT_LOGIN = 60,
DC_STR_CANTDECRYPT_MSG_BODY = 29,
DC_STR_CHAT_PROTECTION_DISABLED = 171,
DC_STR_CHAT_PROTECTION_ENABLED = 170,
DC_STR_CONFIGURATION_FAILED = 84,
DC_STR_CONNECTED = 107,
DC_STR_CONNTECTING = 108,
@@ -231,6 +240,7 @@ export enum C {
DC_STR_MSGGRPNAME = 15,
DC_STR_MSGLOCATIONDISABLED = 65,
DC_STR_MSGLOCATIONENABLED = 64,
DC_STR_NEW_GROUP_SEND_FIRST_MESSAGE = 172,
DC_STR_NOMESSAGES = 1,
DC_STR_NOT_CONNECTED = 121,
DC_STR_NOT_SUPPORTED_BY_PROVIDER = 113,
@@ -238,12 +248,6 @@ export enum C {
DC_STR_OUTGOING_MESSAGES = 104,
DC_STR_PARTIAL_DOWNLOAD_MSG_BODY = 99,
DC_STR_PART_OF_TOTAL_USED = 116,
DC_STR_PROTECTION_DISABLED = 89,
DC_STR_PROTECTION_DISABLED_BY_OTHER = 161,
DC_STR_PROTECTION_DISABLED_BY_YOU = 160,
DC_STR_PROTECTION_ENABLED = 88,
DC_STR_PROTECTION_ENABLED_BY_OTHER = 159,
DC_STR_PROTECTION_ENABLED_BY_YOU = 158,
DC_STR_QUOTA_EXCEEDING_MSG_BODY = 98,
DC_STR_READRCPT = 31,
DC_STR_READRCPT_MAILBODY = 32,
@@ -289,6 +293,7 @@ export const EventId2EventName: { [key: number]: string } = {
103: 'DC_EVENT_SMTP_MESSAGE_SENT',
104: 'DC_EVENT_IMAP_MESSAGE_DELETED',
105: 'DC_EVENT_IMAP_MESSAGE_MOVED',
106: 'DC_EVENT_IMAP_INBOX_IDLE',
150: 'DC_EVENT_NEW_BLOB_FILE',
151: 'DC_EVENT_DELETED_BLOB_FILE',
300: 'DC_EVENT_WARNING',
@@ -302,6 +307,7 @@ export const EventId2EventName: { [key: number]: string } = {
2010: 'DC_EVENT_MSG_DELIVERED',
2012: 'DC_EVENT_MSG_FAILED',
2015: 'DC_EVENT_MSG_READ',
2016: 'DC_EVENT_MSG_DELETED',
2020: 'DC_EVENT_CHAT_MODIFIED',
2021: 'DC_EVENT_CHAT_EPHEMERAL_TIMER_MODIFIED',
2030: 'DC_EVENT_CONTACTS_CHANGED',

View File

@@ -36,7 +36,7 @@ export class Context extends EventEmitter {
}
}
/** Opens a stanalone context (without an account manager)
/** Opens a standalone context (without an account manager)
* automatically starts the event handler */
static open(cwd: string): Context {
const dbFile = join(cwd, 'db.sqlite')
@@ -699,23 +699,6 @@ export class Context extends EventEmitter {
)
}
/**
*
* @param chatId
* @param protect
* @returns success boolean
*/
setChatProtection(chatId: number, protect: boolean) {
debug(`setChatProtection ${chatId} ${protect}`)
return Boolean(
binding.dcn_set_chat_protection(
this.dcn_context,
Number(chatId),
protect ? 1 : 0
)
)
}
getChatEphemeralTimer(chatId: number): number {
debug(`getChatEphemeralTimer ${chatId}`)
return binding.dcn_get_chat_ephemeral_timer(

View File

@@ -21,12 +21,15 @@ export class AccountManager extends EventEmitter {
accountDir: string
jsonRpcStarted = false
constructor(cwd: string, os = 'deltachat-node') {
constructor(cwd: string, writable = true) {
super()
debug('DeltaChat constructor')
this.accountDir = cwd
this.dcn_accounts = binding.dcn_accounts_new(os, this.accountDir)
this.dcn_accounts = binding.dcn_accounts_new(
this.accountDir,
writable ? 1 : 0
)
}
getAllAccountIds() {

View File

@@ -1399,18 +1399,6 @@ NAPI_METHOD(dcn_set_chat_name) {
NAPI_RETURN_INT32(result);
}
NAPI_METHOD(dcn_set_chat_protection) {
NAPI_ARGV(3);
NAPI_DCN_CONTEXT();
NAPI_ARGV_UINT32(chat_id, 1);
NAPI_ARGV_INT32(protect, 1);
int result = dc_set_chat_protection(dcn_context->dc_context,
chat_id,
protect);
NAPI_RETURN_INT32(result);
}
NAPI_METHOD(dcn_get_chat_ephemeral_timer) {
NAPI_ARGV(2);
NAPI_DCN_CONTEXT();
@@ -2915,8 +2903,8 @@ NAPI_METHOD(dcn_msg_get_webxdc_blob){
NAPI_METHOD(dcn_accounts_new) {
NAPI_ARGV(2);
NAPI_ARGV_UTF8_MALLOC(os_name, 0);
NAPI_ARGV_UTF8_MALLOC(dir, 1);
NAPI_ARGV_UTF8_MALLOC(dir, 0);
NAPI_ARGV_INT32(writable, 1);
TRACE("calling..");
dcn_accounts_t* dcn_accounts = calloc(1, sizeof(dcn_accounts_t));
@@ -2925,7 +2913,7 @@ NAPI_METHOD(dcn_accounts_new) {
}
dcn_accounts->dc_accounts = dc_accounts_new(os_name, dir);
dcn_accounts->dc_accounts = dc_accounts_new(dir, writable);
napi_value result;
NAPI_STATUS_THROWS(napi_create_external(env, dcn_accounts,
@@ -3491,7 +3479,6 @@ NAPI_INIT() {
NAPI_EXPORT_FUNCTION(dcn_send_msg);
NAPI_EXPORT_FUNCTION(dcn_send_videochat_invitation);
NAPI_EXPORT_FUNCTION(dcn_set_chat_name);
NAPI_EXPORT_FUNCTION(dcn_set_chat_protection);
NAPI_EXPORT_FUNCTION(dcn_get_chat_ephemeral_timer);
NAPI_EXPORT_FUNCTION(dcn_set_chat_ephemeral_timer);
NAPI_EXPORT_FUNCTION(dcn_set_chat_profile_image);

View File

@@ -8,26 +8,17 @@ import { EventId2EventName, C } from '../dist/constants'
import { join } from 'path'
import { statSync } from 'fs'
import { Context } from '../dist/context'
import fetch from 'node-fetch'
chai.use(chaiAsPromised)
chai.config.truncateThreshold = 0 // Do not truncate assertion errors.
async function createTempUser(url) {
async function postData(url = '') {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'cache-control': 'no-cache',
},
})
if (!response.ok) {
throw new Error('request failed: ' + response.body.read())
}
return response.json() // parses JSON response into native JavaScript objects
function createTempUser(chatmailDomain) {
const charset = "2345789acdefghjkmnpqrstuvwxyz";
let user = "ci-";
for (let i = 0; i < 6; i++) {
user += charset[Math.floor(Math.random() * charset.length)];
}
return await postData(url)
const email = user + "@" + chatmailDomain;
return { email: email, password: user + "$" + user };
}
describe('static tests', function () {
@@ -270,7 +261,7 @@ describe('Basic offline Tests', function () {
'quota_exceeding',
'scan_all_folders_debounce_secs',
'selfavatar',
'send_sync_msgs',
'sync_msgs',
'sentbox_watch',
'show_emails',
'socks5_enabled',
@@ -446,7 +437,8 @@ describe('Offline Tests with unconfigured account', function () {
context.setChatProfileImage(chatId, imagePath)
const blobPath = context.getChat(chatId).getProfileImage()
expect(blobPath.startsWith(blobs)).to.be.true
expect(blobPath.endsWith(image)).to.be.true
expect(blobPath.includes('image')).to.be.true
expect(blobPath.endsWith('.jpeg')).to.be.true
context.setChatProfileImage(chatId, null)
expect(context.getChat(chatId).getProfileImage()).to.be.equal(
@@ -675,9 +667,9 @@ describe('Offline Tests with unconfigured account', function () {
const lot = chatList.getSummary(0)
strictEqual(lot.getId(), 0, 'lot has no id')
strictEqual(lot.getState(), C.DC_STATE_UNDEFINED, 'correct state')
strictEqual(lot.getState(), C.DC_STATE_IN_NOTICED, 'correct state')
const text = 'No messages.'
const text = 'Others will only see this group after you sent a first message.'
context.createGroupChat('groupchat1111')
chatList = context.getChatList(0, 'groupchat1111', null)
strictEqual(
@@ -767,14 +759,7 @@ describe('Integration tests', function () {
})
this.beforeAll(async function () {
if (!process.env.DCC_NEW_TMP_EMAIL) {
console.log(
'Missing DCC_NEW_TMP_EMAIL environment variable!, skip integration tests'
)
this.skip()
}
account = await createTempUser(process.env.DCC_NEW_TMP_EMAIL)
account = createTempUser(process.env.CHATMAIL_DOMAIN)
if (!account || !account.email || !account.password) {
console.log(
"We didn't got back an account from the api, skip integration tests"

View File

@@ -13,10 +13,10 @@
},
"exclude": ["node_modules", "deltachat-core-rust", "dist", "scripts"],
"typedocOptions": {
"mode": "file",
"out": "docs",
"excludeNotExported": true,
"excludePrivate": true,
"defaultCategory": "index",
"includeVersion": true
"includeVersion": true,
"entryPoints": ["lib/index.ts"]
}
}

View File

@@ -6,7 +6,7 @@ E.g via <https://git-scm.com/download/win>
## install node
Download and install `v16` from <https://nodejs.org/en/>
Download and install `v18` from <https://nodejs.org/en/>
## install rust

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