Merge branch 'master' into ep/feed

This commit is contained in:
Evgeny @ SimpleX Chat committed 2026-11-11 16:15:58 +00:00
commit cceb642da4
2412 files changed
+194856 -81641

No files matched your search

-9
View File
@@ -56,15 +56,6 @@ ruff check && pyright && pytest tests/
Wire types under `src/simplex_chat/types/_*.py` are generated. Regenerate with `cabal test simplex-chat-test --test-options='--match Python'`.
## Release
Manual for now. Bump `_version.py:__version__`, build a wheel, upload to PyPI:
```bash
uv build --wheel
uv publish --token "$PYPI_TOKEN"
```
## License
[AGPL-3.0](./LICENSE)
@@ -7,6 +7,7 @@ from __future__ import annotations
import ctypes
import errno
import hashlib
import os
import platform
import sys
@@ -16,9 +17,9 @@ import urllib.request
import zipfile
from ctypes import POINTER, c_char_p, c_int, c_uint8, c_void_p
from pathlib import Path
from typing import Literal
from typing import Any, Literal
from ._version import LIBS_VERSION
from ._version import LIBS_RELEASE, LIBS_SHA256
Backend = Literal["sqlite", "postgres"]
@@ -59,11 +60,14 @@ def _libname() -> str:
return _LIBNAME[sys.platform]
def _libs_url(backend: Backend) -> str:
def _libs_asset(backend: Backend) -> str:
suffix = "-postgres" if backend == "postgres" else ""
return f"simplex-chat-libs-{_platform_tag()}{suffix}.zip"
def _libs_url(backend: Backend) -> str:
return (
f"https://github.com/{_GITHUB_REPO}/releases/download/"
f"v{LIBS_VERSION}/simplex-chat-libs-{_platform_tag()}{suffix}.zip"
f"https://github.com/{_GITHUB_REPO}/releases/download/{LIBS_RELEASE}/{_libs_asset(backend)}"
)
@@ -84,7 +88,7 @@ def _resolve_libs_dir(backend: Backend) -> Path:
"postgres backend is only supported on linux-x86_64; "
f"current platform is {_platform_tag()}"
)
target = _cache_root() / f"v{LIBS_VERSION}" / backend
target = _cache_root() / LIBS_RELEASE / backend
if not (target / _libname()).exists():
_download(target, backend)
return target
@@ -125,16 +129,21 @@ def _download(target: Path, backend: Backend) -> None:
what we need and proceed. NEVER rmtree the target: that creates a TOCTOU
window where another process is reading/loading the file we're deleting.
"""
asset = _libs_asset(backend)
sha256 = LIBS_SHA256.get(asset)
if sha256 is None:
raise RuntimeError(f"no SHA-256 is pinned for {asset}")
target.parent.mkdir(parents=True, exist_ok=True)
url = _libs_url(backend)
print(
f"Downloading libsimplex ({_platform_tag()}, {backend}) v{LIBS_VERSION} from {url} ...",
f"Downloading libsimplex ({_platform_tag()}, {backend}) {LIBS_RELEASE} from {url} ...",
file=sys.stderr,
flush=True,
)
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
zip_path = Path(tmp) / "libs.zip"
_stream_to_file(url, zip_path, timeout=60.0)
_verify_sha256(zip_path, sha256, url)
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(tmp)
# zip layout: <tmp>/libs/libsimplex.* + libHS*.*
@@ -158,6 +167,16 @@ def _download(target: Path, backend: Backend) -> None:
) from e
def _verify_sha256(file: Path, expected: str, url: str) -> None:
digest = hashlib.sha256()
with file.open("rb") as f:
while chunk := f.read(_DOWNLOAD_CHUNK):
digest.update(chunk)
actual = digest.hexdigest()
if actual != expected:
raise RuntimeError(f"SHA-256 of {url} is {actual}, expected {expected}")
_lock = threading.Lock()
_lib: ctypes.CDLL | None = None
_libc: ctypes.CDLL | None = None
@@ -166,7 +185,8 @@ _backend: Backend | None = None
def _load_libc() -> ctypes.CDLL:
if sys.platform == "win32":
return ctypes.CDLL("msvcrt")
# libsimplex.dll allocates results with UCRT malloc; msvcrt free would corrupt the heap.
return ctypes.CDLL("ucrtbase")
return ctypes.CDLL(None) # libc on POSIX is the process's own symbol table
@@ -229,8 +249,8 @@ def lib_for(backend: Backend) -> ctypes.CDLL:
if _lib is not None:
if _backend != backend:
raise RuntimeError(
f"libsimplex already loaded with backend={_backend!r}; "
f"cannot switch to {backend!r} in the same process"
f"libsimplex already loaded with backend={_backend}; "
f"cannot switch to {backend} in the same process"
)
return _lib
libs_dir = _resolve_libs_dir(backend)
@@ -255,3 +275,32 @@ def lib() -> ctypes.CDLL:
if _lib is None:
raise RuntimeError("lib_for() must be called before lib()")
return _lib
def _optional_export(name: str, feature: str, argtypes: list[Any]) -> Any:
try:
fn = getattr(lib(), name)
except AttributeError as e:
raise RuntimeError(
f"loaded libsimplex does not export {name}; {feature} needs a newer libsimplex"
) from e
fn.argtypes = argtypes
fn.restype = c_void_p
return fn
def migrate_init_queue() -> Any:
"""`chat_migrate_init_queue`, which older libsimplex releases do not export."""
return _optional_export(
"chat_migrate_init_queue",
"queue size",
[c_char_p, c_char_p, c_char_p, c_int, POINTER(c_void_p)],
)
def resize_image() -> Any:
return _optional_export("chat_resize_image", "image resizing", [c_char_p, c_int, c_int, c_int])
def resize_image_uri() -> Any:
return _optional_export("chat_resize_image_uri", "image resizing", [c_char_p, c_int, c_int])
@@ -1,9 +1,16 @@
"""Single source of truth for both the Python package version and the
simplex-chat-libs release tag we depend on.
"""Package version and the simplex-chat-libs release it loads.
Bump both together for normal releases. For wrapper-only fixes use a PEP 440
post-release: __version__ = "6.5.2.post1", LIBS_VERSION unchanged.
Written by scripts/ci/packages_release.py prepare: it bumps the version
and pins new library releases with the SHA-256 of their assets.
"""
__version__ = "7.1.0b2" # PEP 440 — read by hatchling for wheel metadata
LIBS_VERSION = "7.1.0-beta.2" # simplex-chat-libs release tag (no 'v' prefix)
__version__ = "7.1.0b6.post2" # PEP 440 — read by hatchling for wheel metadata
LIBS_RELEASE = "core-7.1.0.14" # simplex-chat-libs release tag
LIBS_SHA256 = {
"simplex-chat-libs-linux-aarch64.zip": "375a6021f0c2e5d79b2cd192e17c6c22c8eae73f46e3758fba24ee5c26a671aa",
"simplex-chat-libs-linux-x86_64-postgres.zip": "c3e8a54d37801e685c6361c4e7e53e1f5163d3aa9195dcfe686b6cf90e668ef3",
"simplex-chat-libs-linux-x86_64.zip": "cc41ab9049d61be3b386d799fa9394f2870e8ae3b2b9b8745dd3f53ba99f211e",
"simplex-chat-libs-macos-aarch64.zip": "ac3a46004f25976f71b3ead8a20b9a01c170fe12f125a0a6799ae97ea990f234",
"simplex-chat-libs-macos-x86_64.zip": "0d85ffcccc3a6dfe3e0da18d0b7be9ef36ad27381f047ef66cfde67ee4a7e882",
"simplex-chat-libs-windows-x86_64.zip": "f1d1c7efc333a5ec5328a5843c9d3c9ef038fb2886c0b60ac12e87a5c1e85bbd",
}
@@ -2,7 +2,9 @@
from __future__ import annotations
import asyncio
import json
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Literal
@@ -65,17 +67,20 @@ class ChatApi:
def __init__(self, ctrl: int):
self._ctrl: int | None = ctrl
self._started = False
self._recv_executor: ThreadPoolExecutor | None = None
@classmethod
async def init(
cls,
db: Db,
confirm: MigrationConfirmation = MigrationConfirmation.YES_UP,
queue_size: int | None = None,
) -> ChatApi:
path_or_prefix, key_or_conn, backend = _db_to_migrate_args(db)
# Trigger lazy lib load with the right backend BEFORE chat_migrate_init.
_native.lib_for(backend)
ctrl = await core.chat_migrate_init(path_or_prefix, key_or_conn, confirm)
# It may download ~100 MB, so it must not block the event loop.
await asyncio.to_thread(_native.lib_for, backend)
ctrl = await core.chat_migrate_init(path_or_prefix, key_or_conn, confirm, queue_size)
return cls(ctrl)
@property
@@ -114,6 +119,14 @@ class ChatApi:
self._started = False
async def close(self) -> None:
"""Stop the chat and close its store; the store stays open if stopping fails."""
# a running controller keeps using the database connections that closing frees
await self.stop_chat()
if self._recv_executor is not None:
# Waits for a receive already in flight (up to wait_us) so the store
# never closes underneath one; run off-loop since shutdown blocks.
await asyncio.to_thread(self._recv_executor.shutdown, wait=True)
self._recv_executor = None
await core.chat_close_store(self.ctrl)
self._ctrl = None
self._started = False
@@ -122,7 +135,14 @@ class ChatApi:
return await core.chat_send_cmd(self.ctrl, cmd)
async def recv_chat_event(self, wait_us: int = 500_000) -> CEvt.ChatEvent | None:
return await core.chat_recv_msg_wait(self.ctrl, wait_us)
ctrl = self.ctrl # raises before touching the executor if close() was called
if self._recv_executor is None:
# A receive blocks for up to wait_us almost back to back, so it would
# otherwise pin one of the default executor's few worker threads.
self._recv_executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix="simplex-recv"
)
return await core.chat_recv_msg_wait(ctrl, wait_us, self._recv_executor)
# ------------------------------------------------------------------ #
# Address commands
@@ -158,6 +178,8 @@ class ChatApi:
)
if r["type"] == "userProfileUpdated":
return r["updateSummary"]
if r["type"] == "userProfileNoChange":
return {"updateSuccesses": 0, "updateFailures": 0, "changedContacts": []}
raise ChatCommandError("error setting profile address", r)
async def api_set_address_settings(self, user_id: int, settings: T.AddressSettings) -> None:
@@ -236,6 +258,8 @@ class ChatApi:
)
if r["type"] == "chatItemUpdated":
return r["chatItem"]["chatItem"]
if r["type"] == "chatItemNotChanged":
return r["chatItem"]["chatItem"]
raise ChatCommandError("error updating chat item", r)
async def api_delete_chat_items(
@@ -302,6 +326,8 @@ class ChatApi:
)
if r["type"] == "rcvFileAccepted":
return r["chatItem"]
if r["type"] == "rcvFileAcceptedSndCancelled":
raise ChatCommandError("file cancelled by sender", r)
raise ChatCommandError("error receiving file", r)
async def api_cancel_file(self, file_id: int) -> None:
@@ -325,6 +351,23 @@ class ChatApi:
return r["member"]
raise ChatCommandError("error adding member", r)
async def api_add_member_via_group(
self, group_id: int, via_group_id: int, group_member_id: int, member_role: T.GroupMemberRole
) -> T.GroupMember:
r = await self.send_chat_cmd(
CC.APIAddMemberViaGroup_cmd_string(
{
"groupId": group_id,
"viaGroupId": via_group_id,
"groupMemberId": group_member_id,
"memberRole": member_role,
}
)
)
if r["type"] == "sentGroupInvitationViaGroup":
return r["member"]
raise ChatCommandError("error adding member", r)
async def api_join_group(self, group_id: int) -> T.GroupInfo:
r = await self.send_chat_cmd(CC.APIJoinGroup_cmd_string({"groupId": group_id}))
if r["type"] == "userAcceptedGroupSent":
@@ -477,12 +520,13 @@ class ChatApi:
self,
user_id: int,
incognito: bool,
prepared_link: T.CreatedConnLink | None = None,
prepared_link: T.CreatedConnLink,
) -> ConnReqType:
args: CC.APIConnect = {"userId": user_id, "incognito": incognito}
if prepared_link is not None:
args["preparedLink_"] = prepared_link
r = await self.send_chat_cmd(CC.APIConnect_cmd_string(args))
r = await self.send_chat_cmd(
CC.APIConnect_cmd_string(
{"userId": user_id, "incognito": incognito, "preparedLink_": prepared_link}
)
)
return self._handle_connect_result(r)
async def api_connect_active_user(self, conn_link: str) -> ConnReqType:
@@ -90,11 +90,13 @@ class Bot(Client):
welcome: str | T.MsgContent | None = None,
commands: list[BotCommand] | None = None,
confirm_migrations: MigrationConfirmation = MigrationConfirmation.YES_UP,
queue_size: int | None = None,
create_address: bool = True,
update_address: bool = True,
update_profile: bool = True,
auto_accept: bool = True,
business_address: bool = False,
chat_layout: T.ChatLayout | None = None,
allow_files: bool = False,
log_contacts: bool = True,
log_network: bool = False,
@@ -103,6 +105,7 @@ class Bot(Client):
profile=profile,
db=db,
confirm_migrations=confirm_migrations,
queue_size=queue_size,
update_profile=update_profile,
log_contacts=log_contacts,
log_network=log_network,
@@ -113,6 +116,7 @@ class Bot(Client):
self._update_address = update_address
self._auto_accept = auto_accept
self._business_address = business_address
self._chat_layout = chat_layout
self._allow_files = allow_files
# ------------------------------------------------------------------ #
@@ -151,6 +155,8 @@ class Bot(Client):
desired: T.AddressSettings = {"businessAddress": self._business_address}
if self._auto_accept:
desired["autoAccept"] = {"acceptIncognito": False}
if self._chat_layout is not None:
desired["chatLayout"] = self._chat_layout
if self._welcome is not None:
desired["autoReply"] = (
{"type": "text", "text": self._welcome}
@@ -149,6 +149,7 @@ class Client:
profile: Profile,
db: Db,
confirm_migrations: MigrationConfirmation = MigrationConfirmation.YES_UP,
queue_size: int | None = None,
update_profile: bool = True,
log_contacts: bool = False,
log_network: bool = False,
@@ -156,6 +157,7 @@ class Client:
self._profile = profile
self._db = db
self._confirm_migrations = confirm_migrations
self._queue_size = queue_size
self._update_profile = update_profile
self._log_contacts = log_contacts
self._log_network = log_network
@@ -343,7 +345,7 @@ class Client:
# do post-start setup (profile sync; Bot adds address sync).
# `_stop_event` is never cleared: a stop requested during startup has
# to survive into the receive loop. A stopped client is spent.
self._api = await ChatApi.init(self._db, self._confirm_migrations)
self._api = await ChatApi.init(self._db, self._confirm_migrations, self._queue_size)
try:
user = await self._ensure_active_user()
await self._api.start_chat()
@@ -362,11 +364,6 @@ class Client:
api = self._api
if api is None:
return
if api.started:
try:
await api.stop_chat()
except Exception:
log.exception("stop_chat failed during init rollback")
try:
await api.close()
except Exception:
@@ -379,13 +376,16 @@ class Client:
if api is None:
return
# Null out the reference up-front so the Client appears closed even
# if stop_chat / close raise — otherwise `client.api` would still
# if close raises — otherwise `client.api` would still
# hand back a half-shutdown controller after `async with` exits.
self._api = None
try:
await api.stop_chat()
finally:
await api.close()
except BaseException:
# A failed stop leaves the store open; keep it so the caller can retry.
if api.initialized:
self._api = api
raise
async def _post_start(self, user: T.User) -> None:
"""Hook for subclasses to add work between `start_chat` and serving.
@@ -617,7 +617,7 @@ class Client:
# message resolve a future no one is waiting on.
if waiter in waiters:
waiters.remove(waiter)
if not waiters:
if not waiters and self._reply_waiters.get(contact_id) is waiters:
self._reply_waiters.pop(contact_id, None)
async def _receive_loop(self) -> None:
@@ -1,16 +1,19 @@
"""Internal typed async wrapper around libsimplex's 8 C ABI functions.
"""Typed async wrapper around libsimplex's C ABI functions.
Users interact with `Bot` / `ChatApi`. This module is exposed as
`simplex_chat.core` for tests and the api.ChatApi class only.
`simplex_chat.core` for tests, the api.ChatApi class and image resizing
(`resize_image`, `chat_resize_image`, `chat_resize_image_uri`).
"""
from __future__ import annotations
import asyncio
import base64
import ctypes
import json
from concurrent.futures import Executor
from enum import StrEnum
from typing import Any, TypedDict
from typing import Any, Literal, TypedDict, overload
from . import _native
from .types import CR, CEvt, T
@@ -69,6 +72,12 @@ class MigrationConfirmation(StrEnum):
ERROR = "error"
class ImageSize(StrEnum):
IMAGE = "image"
PROFILE_PREVIEW = "profilePreview"
MESSAGE_PREVIEW = "messagePreview"
class CryptoArgs(TypedDict): # wire-format JSON; camelCase fields
fileKey: str
fileNonce: str
@@ -87,6 +96,12 @@ def _read_and_free(ptr: int | None) -> str:
_native.libc().free(ctypes.c_void_p(ptr))
def _check_c_int(name: str, value: int) -> None:
# ctypes silently wraps ints that do not fit C int.
if ctypes.c_int(value).value != value:
raise ValueError(f"{name} {value} does not fit C int")
async def chat_send_cmd(ctrl: int, cmd: str) -> CR.ChatResponse:
def _call() -> str:
ptr = _native.lib().chat_send_cmd(ctrl, cmd.encode("utf-8"))
@@ -102,7 +117,9 @@ async def chat_send_cmd(ctrl: int, cmd: str) -> CR.ChatResponse:
raise ChatAPIError(f"invalid chat command result: {raw[:200]}")
async def chat_recv_msg_wait(ctrl: int, wait_us: int = 500_000) -> CEvt.ChatEvent | None:
async def chat_recv_msg_wait(
ctrl: int, wait_us: int = 500_000, executor: Executor | None = None
) -> CEvt.ChatEvent | None:
def _call() -> str:
# On timeout, the C side returns a non-NULL pointer to a single NUL byte
# (see Mobile.hs `fromMaybe ""`), so `_read_and_free` returns "" — no
@@ -110,7 +127,10 @@ async def chat_recv_msg_wait(ctrl: int, wait_us: int = 500_000) -> CEvt.ChatEven
ptr = _native.lib().chat_recv_msg_wait(ctrl, wait_us)
return _read_and_free(ptr)
raw = await asyncio.to_thread(_call)
if executor is None:
raw = await asyncio.to_thread(_call)
else:
raw = await asyncio.get_running_loop().run_in_executor(executor, _call)
if not raw:
return None
parsed = json.loads(raw)
@@ -122,17 +142,28 @@ async def chat_recv_msg_wait(ctrl: int, wait_us: int = 500_000) -> CEvt.ChatEven
raise ChatAPIError(f"invalid chat event: {raw[:200]}")
async def chat_migrate_init(db_path: str, db_key: str, confirm: MigrationConfirmation) -> int:
"""Initialize chat controller. Returns opaque ctrl pointer as Python int."""
async def chat_migrate_init(
db_path: str,
db_key: str,
confirm: MigrationConfirmation,
queue_size: int | None = None,
) -> int:
"""Initialize chat controller. Returns opaque ctrl pointer as Python int.
`queue_size` is the size of internal queues; the core default is used when None.
"""
if queue_size is not None:
_check_c_int("queue_size", queue_size)
init_queue = _native.migrate_init_queue() if queue_size is not None else None
def _call() -> tuple[int, str]:
ctrl = ctypes.c_void_p()
ptr = _native.lib().chat_migrate_init(
db_path.encode("utf-8"),
db_key.encode("utf-8"),
confirm.encode("utf-8"),
ctypes.byref(ctrl),
)
args = (db_path.encode("utf-8"), db_key.encode("utf-8"), confirm.encode("utf-8"))
if init_queue is None:
ptr = _native.lib().chat_migrate_init(*args, ctypes.byref(ctrl))
else:
ptr = init_queue(*args, queue_size, ctypes.byref(ctrl))
return (ctrl.value or 0, _read_and_free(ptr))
ctrl_val, raw = await asyncio.to_thread(_call)
@@ -228,3 +259,62 @@ def _crypto_args_result(raw: str) -> CryptoArgs:
if parsed.get("type") == "error":
raise RuntimeError(parsed.get("writeError", "unknown write error"))
raise RuntimeError(f"unexpected result: {raw[:200]}")
async def chat_resize_image_uri(data: bytes, max_size: int) -> str:
_check_c_int("len(data)", len(data))
_check_c_int("max_size", max_size)
resize = _native.resize_image_uri()
def _call() -> str:
return _read_and_free(resize(data, len(data), max_size))
return _resized_image(await asyncio.to_thread(_call))
async def chat_resize_image(
data: bytes, max_size: int, image_format: Literal["jpeg", "png"]
) -> bytes:
return await _resize_image_data(data, max_size, 1 if image_format == "png" else 0)
@overload
async def resize_image(data: bytes, size: Literal[ImageSize.IMAGE]) -> bytes: ...
@overload
async def resize_image(
data: bytes, size: Literal[ImageSize.PROFILE_PREVIEW, ImageSize.MESSAGE_PREVIEW]
) -> str: ...
@overload
async def resize_image(data: bytes, size: ImageSize) -> bytes | str: ...
async def resize_image(data: bytes, size: ImageSize) -> bytes | str:
"""Resize image to the app size limit: JPEG or PNG for an image, a data URI for a preview."""
match size:
case ImageSize.IMAGE:
return await _resize_image_data(data, 261120, -1)
case ImageSize.PROFILE_PREVIEW:
return await chat_resize_image_uri(data, 12500)
case ImageSize.MESSAGE_PREVIEW:
return await chat_resize_image_uri(data, 14000)
async def _resize_image_data(data: bytes, max_size: int, png: int) -> bytes:
_check_c_int("len(data)", len(data))
_check_c_int("max_size", max_size)
resize = _native.resize_image()
def _call() -> str:
return _read_and_free(resize(data, len(data), max_size, png))
return base64.b64decode(_resized_image(await asyncio.to_thread(_call)))
def _resized_image(res: str) -> str:
if not res:
raise RuntimeError("image cannot be decoded or does not fit max_size")
return res
@@ -59,6 +59,19 @@ def APISetProfileAddress_cmd_string(self: APISetProfileAddress) -> str:
APISetProfileAddress_Response = CR.UserProfileUpdated | CR.UserProfileNoChange | CR.ChatCmdError
# Set or remove SimpleX name of bot address. The name must be registered with the address short link.
# Network usage: interactive.
class APISetUserDomain(TypedDict):
userId: int # int64
simplexDomain: NotRequired[str]
def APISetUserDomain_cmd_string(self: APISetUserDomain) -> str:
return '/_set domain ' + str(self['userId']) + ((' ' + self.get('simplexDomain')) if self.get('simplexDomain') is not None else '')
APISetUserDomain_Response = CR.UserProfileUpdated | CR.UserProfileNoChange | CR.ChatCmdError
# Set bot address settings.
# Network usage: interactive.
class APISetAddressSettings(TypedDict):
@@ -222,6 +235,21 @@ def APIAddMember_cmd_string(self: APIAddMember) -> str:
APIAddMember_Response = CR.SentGroupInvitation | CR.ChatCmdError
# Add member of another group to group. Requires bot to have Admin role in the group, and direct messages allowed for its role in another group.
# Network usage: interactive.
class APIAddMemberViaGroup(TypedDict):
groupId: int # int64
viaGroupId: int # int64
groupMemberId: int # int64
memberRole: "T.GroupMemberRole"
def APIAddMemberViaGroup_cmd_string(self: APIAddMemberViaGroup) -> str:
return '/_add #' + str(self['groupId']) + ' #' + str(self['viaGroupId']) + ' ' + str(self['groupMemberId']) + ' ' + str(self['memberRole'])
APIAddMemberViaGroup_Response = CR.SentGroupInvitationViaGroup | CR.ChatCmdError
# Join group.
# Network usage: interactive.
class APIJoinGroup(TypedDict):
@@ -314,6 +342,32 @@ def APIListMembers_cmd_string(self: APIListMembers) -> str:
APIListMembers_Response = CR.GroupMembers | CR.ChatCmdError
# Create a direct message contact with a group member.
# Network usage: interactive.
class APICreateMemberContact(TypedDict):
groupId: int # int64
groupMemberId: int # int64
def APICreateMemberContact_cmd_string(self: APICreateMemberContact) -> str:
return '/_create member contact #' + str(self['groupId']) + ' ' + str(self['groupMemberId'])
APICreateMemberContact_Response = CR.NewMemberContact | CR.ChatCmdError
# Send a direct message invitation to a group member contact.
# Network usage: background.
class APISendMemberContactInvitation(TypedDict):
contactId: int # int64
msgContent_: NotRequired["T.MsgContent"]
def APISendMemberContactInvitation_cmd_string(self: APISendMemberContactInvitation) -> str:
return '/_invite member contact @' + str(self['contactId']) + ((' json ' + json.dumps(self.get('msgContent_'))) if self.get('msgContent_') is not None else '')
APISendMemberContactInvitation_Response = CR.NewMemberContactSentInv | CR.ChatCmdError
# Create group.
# Network usage: no.
class APINewGroup(TypedDict):
@@ -484,7 +538,7 @@ class APIConnectPlan(TypedDict):
def APIConnectPlan_cmd_string(self: APIConnectPlan) -> str:
return '/_connect plan ' + str(self['userId']) + ' ' + self.get('connectTarget')
return '/_connect plan ' + str(self['userId']) + ' ' + self.get('connectTarget') + T.PlanResolveMode_cmd_string(self['resolveMode']) + ((' sig=' + json.dumps(self.get('linkOwnerSig'))) if self.get('linkOwnerSig') is not None else '')
APIConnectPlan_Response = CR.ConnectionPlan | CR.ChatCmdError
@@ -498,7 +552,7 @@ class APIConnect(TypedDict):
def APIConnect_cmd_string(self: APIConnect) -> str:
return '/_connect ' + str(self['userId']) + ((' ' + T.CreatedConnLink_cmd_string(self.get('preparedLink_'))) if self.get('preparedLink_') is not None else '')
return '/_connect ' + str(self['userId']) + (' incognito=on' if self['incognito'] else '') + ((' ' + T.CreatedConnLink_cmd_string(self.get('preparedLink_'))) if self.get('preparedLink_') is not None else '')
APIConnect_Response = CR.SentConfirmation | CR.ContactAlreadyExists | CR.SentInvitation | CR.ChatCmdError
@@ -525,6 +579,80 @@ Connect_Response = (
)
# Prepare contact chat from link data before connecting.
# Network usage: no.
class APIPrepareContact(TypedDict):
userId: int # int64
connLink: "T.CreatedConnLink"
verifiedDomain: NotRequired[str]
contactSLinkData: "T.ContactShortLinkData"
def APIPrepareContact_cmd_string(self: APIPrepareContact) -> str:
return '/_prepare contact ' + str(self['userId']) + ' ' + T.CreatedConnLink_cmd_string(self['connLink']) + ((' domain=' + self.get('verifiedDomain')) if self.get('verifiedDomain') is not None else '') + ' ' + json.dumps(self['contactSLinkData'])
APIPrepareContact_Response = CR.NewPreparedChat | CR.ChatCmdError
# Prepare group chat from link data before connecting.
# Network usage: no.
class APIPrepareGroup(TypedDict):
userId: int # int64
connLinkContact: "T.CreatedConnLink"
direct: bool
verifiedDomain: NotRequired[str]
groupSLinkData: "T.GroupShortLinkData"
def APIPrepareGroup_cmd_string(self: APIPrepareGroup) -> str:
return '/_prepare group ' + str(self['userId']) + ' ' + T.CreatedConnLink_cmd_string(self['connLinkContact']) + (' direct=off' if not self['direct'] else '') + ((' domain=' + self.get('verifiedDomain')) if self.get('verifiedDomain') is not None else '') + ' ' + json.dumps(self['groupSLinkData'])
APIPrepareGroup_Response = CR.NewPreparedChat | CR.ChatCmdError
# Connect to prepared contact.
# Network usage: interactive.
class APIConnectPreparedContact(TypedDict):
contactId: int # int64
incognito: bool
msgContent_: NotRequired["T.MsgContent"]
def APIConnectPreparedContact_cmd_string(self: APIConnectPreparedContact) -> str:
return '/_connect contact @' + str(self['contactId']) + (' incognito=on' if self['incognito'] else '') + ((' json ' + json.dumps(self.get('msgContent_'))) if self.get('msgContent_') is not None else '')
APIConnectPreparedContact_Response = CR.StartedConnectionToContact | CR.ContactAlreadyExists | CR.ChatCmdError
# Connect to prepared group.
# Network usage: interactive.
class APIConnectPreparedGroup(TypedDict):
groupId: int # int64
incognito: bool
ownerContact: NotRequired["T.GroupOwnerContact"]
msgContent_: NotRequired["T.MsgContent"]
def APIConnectPreparedGroup_cmd_string(self: APIConnectPreparedGroup) -> str:
return '/_connect group #' + str(self['groupId']) + (' incognito=on' if self['incognito'] else '') + ((' ' + T.GroupOwnerContact_cmd_string(self.get('ownerContact'))) if self.get('ownerContact') is not None else '') + ((' json ' + json.dumps(self.get('msgContent_'))) if self.get('msgContent_') is not None else '')
APIConnectPreparedGroup_Response = CR.StartedConnectionToGroup | CR.ChatCmdError
# Connect to existing contact via address in its profile.
# Network usage: interactive.
class APIConnectContactViaAddress(TypedDict):
userId: int # int64
incognito: bool
contactId: int # int64
def APIConnectContactViaAddress_cmd_string(self: APIConnectContactViaAddress) -> str:
return '/_connect contact ' + str(self['userId']) + (' incognito=on' if self['incognito'] else '') + ' ' + str(self['contactId'])
APIConnectContactViaAddress_Response = CR.SentInvitationToContact | CR.ChatCmdError
# Accept contact request.
# Network usage: interactive.
class APIAcceptContact(TypedDict):
@@ -584,16 +712,69 @@ APIListGroups_Response = CR.GroupsList | CR.ChatCmdError
class APIGetChats(TypedDict):
userId: int # int64
pendingConnections: bool
pagination: "T.PaginationByTime"
pagination: NotRequired["T.PaginationByTime"]
query: "T.ChatListQuery"
def APIGetChats_cmd_string(self: APIGetChats) -> str:
return '/_get chats ' + str(self['userId']) + (' pcc=on' if self['pendingConnections'] else '') + ' ' + T.PaginationByTime_cmd_string(self['pagination']) + ' ' + json.dumps(self['query'])
return '/_get chats ' + str(self['userId']) + (' pcc=on' if self['pendingConnections'] else '') + ((' ' + T.PaginationByTime_cmd_string(self.get('pagination'))) if self.get('pagination') is not None else '') + ' ' + json.dumps(self['query'])
APIGetChats_Response = CR.ApiChats | CR.ChatCmdError
# Get chat messages.
# Network usage: no.
class APIGetChat(TypedDict):
chatRef: "T.ChatRef"
contentTag: NotRequired["T.MsgContentTag"]
chatPagination: "T.ChatPagination"
search: NotRequired[str]
def APIGetChat_cmd_string(self: APIGetChat) -> str:
return '/_get chat ' + T.ChatRef_cmd_string(self['chatRef']) + ((' content=' + str(self.get('contentTag'))) if self.get('contentTag') is not None else '') + ' ' + T.ChatPagination_cmd_string(self['chatPagination']) + ((' search=' + self.get('search')) if self.get('search') is not None else '')
APIGetChat_Response = CR.ApiChat | CR.ChatCmdError
# Mark messages as read.
# Network usage: no.
class APIChatItemsRead(TypedDict):
chatRef: "T.ChatRef"
chatItemIds: list[int] # int64, non-empty
def APIChatItemsRead_cmd_string(self: APIChatItemsRead) -> str:
return '/_read chat items ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + ','.join(map(str, self['chatItemIds']))
APIChatItemsRead_Response = CR.ItemsReadForChat | CR.ChatCmdError
# Get contact information.
# Network usage: no.
class APIContactInfo(TypedDict):
contactId: int # int64
def APIContactInfo_cmd_string(self: APIContactInfo) -> str:
return '/_info @' + str(self['contactId'])
APIContactInfo_Response = CR.ContactInfo | CR.ChatCmdError
# Get message information.
# Network usage: no.
class APIGetChatItemInfo(TypedDict):
chatRef: "T.ChatRef"
chatItemId: int # int64
def APIGetChatItemInfo_cmd_string(self: APIGetChatItemInfo) -> str:
return '/_get item info ' + T.ChatRef_cmd_string(self['chatRef']) + ' ' + str(self['chatItemId'])
APIGetChatItemInfo_Response = CR.ChatItemInfo | CR.ChatCmdError
# Delete chat.
# Network usage: background.
class APIDeleteChat(TypedDict):
@@ -797,6 +978,42 @@ def APIStopChat_cmd_string(self: APIStopChat) -> str:
APIStopChat_Response = CR.ChatStopped
# Get network configuration.
# Network usage: no.
class APIGetNetworkConfig(TypedDict):
pass
def APIGetNetworkConfig_cmd_string(self: APIGetNetworkConfig) -> str:
return '/network'
APIGetNetworkConfig_Response = CR.NetworkConfig | CR.ChatCmdError
# Set network configuration.
# Network usage: background.
class APISetNetworkConfig(TypedDict):
networkConfig: "T.NetworkConfig"
def APISetNetworkConfig_cmd_string(self: APISetNetworkConfig) -> str:
return '/_network ' + json.dumps(self['networkConfig'])
APISetNetworkConfig_Response = CR.CmdOk | CR.ChatCmdError
# Get user servers and chat relays, grouped by operator.
# Network usage: no.
class APIGetUserServers(TypedDict):
userId: int # int64
def APIGetUserServers_cmd_string(self: APIGetUserServers) -> str:
return '/_servers ' + str(self['userId'])
APIGetUserServers_Response = CR.UserServers | CR.ChatCmdError
# Remote control commands
# Allows a bot to accept an incoming remote control session from a SimpleX Desktop client, giving the desktop live access to the bot's SimpleX instance.
@@ -84,6 +84,15 @@ class ReceivedGroupInvitation(TypedDict):
fromMemberRole: "T.GroupMemberRole"
memberRole: "T.GroupMemberRole"
class ReceivedGroupInvitationViaGroup(TypedDict):
type: Literal["receivedGroupInvitationViaGroup"]
user: "T.User"
groupInfo: "T.GroupInfo"
viaGroupInfo: "T.GroupInfo"
viaMember: "T.GroupMember"
fromMemberRole: "T.GroupMemberRole"
memberRole: "T.GroupMemberRole"
class UserJoinedGroup(TypedDict):
type: Literal["userJoinedGroup"]
user: "T.User"
@@ -352,6 +361,7 @@ ChatEvent = (
| GroupChatItemsDeleted
| ChatItemsStatusesUpdated
| ReceivedGroupInvitation
| ReceivedGroupInvitationViaGroup
| UserJoinedGroup
| GroupUpdated
| JoinedGroupMember
@@ -394,7 +404,7 @@ ChatEvent = (
| ChatErrors
)
ChatEvent_Tag = Literal["contactConnected", "contactUpdated", "contactDeletedByContact", "receivedContactRequest", "newMemberContactReceivedInv", "contactSndReady", "newChatItems", "chatItemReaction", "chatItemsDeleted", "chatItemUpdated", "groupChatItemsDeleted", "chatItemsStatusesUpdated", "receivedGroupInvitation", "userJoinedGroup", "groupUpdated", "joinedGroupMember", "memberRole", "deletedMember", "leftMember", "deletedMemberUser", "groupDeleted", "connectedToGroupMember", "memberAcceptedByOther", "memberBlockedForAll", "groupMemberUpdated", "groupLinkDataUpdated", "groupRelayUpdated", "rcvFileDescrReady", "rcvFileComplete", "sndFileCompleteXFTP", "rcvFileStart", "rcvFileSndCancelled", "rcvFileAccepted", "rcvFileError", "rcvFileWarning", "sndFileError", "sndFileWarning", "acceptingContactRequest", "acceptingBusinessRequest", "contactConnecting", "businessLinkConnecting", "joinedGroupMemberConnecting", "groupLinkConnecting", "hostConnected", "hostDisconnected", "subscriptionStatus", "serviceRequest", "serviceReplySent", "remoteCtrlSessionCode", "remoteCtrlStopped", "messageError", "chatError", "chatErrors"]
ChatEvent_Tag = Literal["contactConnected", "contactUpdated", "contactDeletedByContact", "receivedContactRequest", "newMemberContactReceivedInv", "contactSndReady", "newChatItems", "chatItemReaction", "chatItemsDeleted", "chatItemUpdated", "groupChatItemsDeleted", "chatItemsStatusesUpdated", "receivedGroupInvitation", "receivedGroupInvitationViaGroup", "userJoinedGroup", "groupUpdated", "joinedGroupMember", "memberRole", "deletedMember", "leftMember", "deletedMemberUser", "groupDeleted", "connectedToGroupMember", "memberAcceptedByOther", "memberBlockedForAll", "groupMemberUpdated", "groupLinkDataUpdated", "groupRelayUpdated", "rcvFileDescrReady", "rcvFileComplete", "sndFileCompleteXFTP", "rcvFileStart", "rcvFileSndCancelled", "rcvFileAccepted", "rcvFileError", "rcvFileWarning", "sndFileError", "sndFileWarning", "acceptingContactRequest", "acceptingBusinessRequest", "contactConnecting", "businessLinkConnecting", "joinedGroupMemberConnecting", "groupLinkConnecting", "hostConnected", "hostDisconnected", "subscriptionStatus", "serviceRequest", "serviceReplySent", "remoteCtrlSessionCode", "remoteCtrlStopped", "messageError", "chatError", "chatErrors"]
class OnEventDecorator(Protocol):
@@ -483,6 +493,12 @@ class OnEventDecorator(Protocol):
Callable[["ReceivedGroupInvitation"], Awaitable[None]],
]: ...
@overload
def __call__(self, event: Literal["receivedGroupInvitationViaGroup"], /) -> Callable[
[Callable[["ReceivedGroupInvitationViaGroup"], Awaitable[None]]],
Callable[["ReceivedGroupInvitationViaGroup"], Awaitable[None]],
]: ...
@overload
def __call__(self, event: Literal["userJoinedGroup"], /) -> Callable[
[Callable[["UserJoinedGroup"], Awaitable[None]]],
@@ -13,6 +13,18 @@ class ActiveUser(TypedDict):
type: Literal["activeUser"]
user: "T.User"
class ApiChat(TypedDict):
type: Literal["apiChat"]
user: "T.User"
chat: "T.AChat"
navInfo: NotRequired["T.NavigationInfo"]
class ChatItemInfo(TypedDict):
type: Literal["chatItemInfo"]
user: "T.User"
chatItem: "T.AChatItem"
chatItemInfo: "T.ChatItemInfo"
class ChatItemNotChanged(TypedDict):
type: Literal["chatItemNotChanged"]
user: "T.User"
@@ -81,6 +93,13 @@ class ContactDeleted(TypedDict):
user: "T.User"
contact: "T.Contact"
class ContactInfo(TypedDict):
type: Literal["contactInfo"]
user: "T.User"
contact: "T.Contact"
connectionStats_: NotRequired["T.ConnectionStats"]
customUserProfile: NotRequired["T.Profile"]
class ContactPrefsUpdated(TypedDict):
type: Literal["contactPrefsUpdated"]
user: "T.User"
@@ -192,6 +211,11 @@ class Invitation(TypedDict):
connLinkInvitation: "T.CreatedConnLink"
connection: "T.PendingContactConnection"
class ItemsReadForChat(TypedDict):
type: Literal["itemsReadForChat"]
user: "T.User"
chatInfo: "T.ChatInfo"
class LeftMemberUser(TypedDict):
type: Literal["leftMemberUser"]
user: "T.User"
@@ -219,11 +243,34 @@ class MembersRoleUser(TypedDict):
toRole: "T.GroupMemberRole"
msgSigned: bool
class NetworkConfig(TypedDict):
type: Literal["networkConfig"]
networkConfig: "T.NetworkConfig"
class NewChatItems(TypedDict):
type: Literal["newChatItems"]
user: "T.User"
chatItems: list["T.AChatItem"]
class NewMemberContact(TypedDict):
type: Literal["newMemberContact"]
user: "T.User"
contact: "T.Contact"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
class NewMemberContactSentInv(TypedDict):
type: Literal["newMemberContactSentInv"]
user: "T.User"
contact: "T.Contact"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
class NewPreparedChat(TypedDict):
type: Literal["newPreparedChat"]
user: "T.User"
chat: "T.AChat"
class RcvFileAccepted(TypedDict):
type: Literal["rcvFileAccepted"]
user: "T.User"
@@ -264,6 +311,14 @@ class SentGroupInvitation(TypedDict):
contact: "T.Contact"
member: "T.GroupMember"
class SentGroupInvitationViaGroup(TypedDict):
type: Literal["sentGroupInvitationViaGroup"]
user: "T.User"
groupInfo: "T.GroupInfo"
member: "T.GroupMember"
viaGroupInfo: "T.GroupInfo"
viaMember: "T.GroupMember"
class SentInvitation(TypedDict):
type: Literal["sentInvitation"]
user: "T.User"
@@ -345,6 +400,11 @@ class UserProfileNoChange(TypedDict):
type: Literal["userProfileNoChange"]
user: "T.User"
class UserServers(TypedDict):
type: Literal["userServers"]
user: "T.User"
userServers: list["T.UserOperatorServers"]
class UsersList(TypedDict):
type: Literal["usersList"]
users: list["T.UserInfo"]
@@ -357,6 +417,8 @@ class ApiChats(TypedDict):
ChatResponse = (
AcceptingContactRequest
| ActiveUser
| ApiChat
| ChatItemInfo
| ChatItemNotChanged
| ChatItemReaction
| ChatItemUpdated
@@ -371,6 +433,7 @@ ChatResponse = (
| ContactAlreadyExists
| ContactConnectionDeleted
| ContactDeleted
| ContactInfo
| ContactPrefsUpdated
| ContactRequestRejected
| ContactsList
@@ -390,11 +453,16 @@ ChatResponse = (
| GroupsList
| GroupDomainVerified
| Invitation
| ItemsReadForChat
| LeftMemberUser
| MemberAccepted
| MembersBlockedForAllUser
| MembersRoleUser
| NetworkConfig
| NewChatItems
| NewMemberContact
| NewMemberContactSentInv
| NewPreparedChat
| RcvFileAccepted
| RcvFileAcceptedSndCancelled
| RcvFileCancelled
@@ -402,6 +470,7 @@ ChatResponse = (
| RemoteCtrlConnecting
| SentConfirmation
| SentGroupInvitation
| SentGroupInvitationViaGroup
| SentInvitation
| SentInvitationToContact
| ServiceReplyAccepted
@@ -416,8 +485,9 @@ ChatResponse = (
| UserDeletedMembers
| UserProfileUpdated
| UserProfileNoChange
| UserServers
| UsersList
| ApiChats
)
ChatResponse_Tag = Literal["acceptingContactRequest", "activeUser", "chatItemNotChanged", "chatItemReaction", "chatItemUpdated", "chatItemsDeleted", "chatMsgContent", "chatRunning", "chatStarted", "chatStopped", "cmdOk", "chatCmdError", "connectionPlan", "contactAlreadyExists", "contactConnectionDeleted", "contactDeleted", "contactPrefsUpdated", "contactRequestRejected", "contactsList", "groupDeletedUser", "groupLink", "groupLinkCreated", "groupLinkDeleted", "groupCreated", "publicGroupCreated", "publicGroupCreationFailed", "groupRelays", "groupRelaysAdded", "groupRelaysAddFailed", "relayGroupAllowed", "groupMembers", "groupUpdated", "groupsList", "groupDomainVerified", "invitation", "leftMemberUser", "memberAccepted", "membersBlockedForAllUser", "membersRoleUser", "newChatItems", "rcvFileAccepted", "rcvFileAcceptedSndCancelled", "rcvFileCancelled", "remoteCtrlConnected", "remoteCtrlConnecting", "sentConfirmation", "sentGroupInvitation", "sentInvitation", "sentInvitationToContact", "serviceReplyAccepted", "sndFileCancelled", "startedConnectionToContact", "startedConnectionToGroup", "userAcceptedGroupSent", "userContactLink", "userContactLinkCreated", "userContactLinkDeleted", "userContactLinkUpdated", "userDeletedMembers", "userProfileUpdated", "userProfileNoChange", "usersList", "apiChats"]
ChatResponse_Tag = Literal["acceptingContactRequest", "activeUser", "apiChat", "chatItemInfo", "chatItemNotChanged", "chatItemReaction", "chatItemUpdated", "chatItemsDeleted", "chatMsgContent", "chatRunning", "chatStarted", "chatStopped", "cmdOk", "chatCmdError", "connectionPlan", "contactAlreadyExists", "contactConnectionDeleted", "contactDeleted", "contactInfo", "contactPrefsUpdated", "contactRequestRejected", "contactsList", "groupDeletedUser", "groupLink", "groupLinkCreated", "groupLinkDeleted", "groupCreated", "publicGroupCreated", "publicGroupCreationFailed", "groupRelays", "groupRelaysAdded", "groupRelaysAddFailed", "relayGroupAllowed", "groupMembers", "groupUpdated", "groupsList", "groupDomainVerified", "invitation", "itemsReadForChat", "leftMemberUser", "memberAccepted", "membersBlockedForAllUser", "membersRoleUser", "networkConfig", "newChatItems", "newMemberContact", "newMemberContactSentInv", "newPreparedChat", "rcvFileAccepted", "rcvFileAcceptedSndCancelled", "rcvFileCancelled", "remoteCtrlConnected", "remoteCtrlConnecting", "sentConfirmation", "sentGroupInvitation", "sentGroupInvitationViaGroup", "sentInvitation", "sentInvitationToContact", "serviceReplyAccepted", "sndFileCancelled", "startedConnectionToContact", "startedConnectionToGroup", "userAcceptedGroupSent", "userContactLink", "userContactLinkCreated", "userContactLinkDeleted", "userContactLinkUpdated", "userDeletedMembers", "userProfileUpdated", "userProfileNoChange", "userServers", "usersList", "apiChats"]
@@ -23,6 +23,7 @@ class AddRelayResult(TypedDict):
class AddressSettings(TypedDict):
businessAddress: bool
autoAccept: NotRequired["AutoAccept"]
chatLayout: NotRequired["ChatLayout"]
autoReply: NotRequired["MsgContent"]
class AgentCryptoError_DECRYPT_AES(TypedDict):
@@ -185,10 +186,126 @@ class BadgeProof(TypedDict):
proof: str
badgeInfo: "BadgeInfo"
class BadgeRedeemError_invalidCode(TypedDict):
type: Literal["invalidCode"]
class BadgeRedeemError_invalidReceipt(TypedDict):
type: Literal["invalidReceipt"]
class BadgeRedeemError_serviceNotConfigured(TypedDict):
type: Literal["serviceNotConfigured"]
class BadgeRedeemError_badgeActive(TypedDict):
type: Literal["badgeActive"]
class BadgeRedeemError_storePurchaseOpen(TypedDict):
type: Literal["storePurchaseOpen"]
class BadgeRedeemError_serviceError(TypedDict):
type: Literal["serviceError"]
serviceError: "BadgeServiceErrorCode"
class BadgeRedeemError_invalidResponse(TypedDict):
type: Literal["invalidResponse"]
message: str
class BadgeRedeemError_unknownKeyIndex(TypedDict):
type: Literal["unknownKeyIndex"]
class BadgeRedeemError_credentialNotVerified(TypedDict):
type: Literal["credentialNotVerified"]
BadgeRedeemError = (
BadgeRedeemError_invalidCode
| BadgeRedeemError_invalidReceipt
| BadgeRedeemError_serviceNotConfigured
| BadgeRedeemError_badgeActive
| BadgeRedeemError_storePurchaseOpen
| BadgeRedeemError_serviceError
| BadgeRedeemError_invalidResponse
| BadgeRedeemError_unknownKeyIndex
| BadgeRedeemError_credentialNotVerified
)
BadgeRedeemError_Tag = Literal["invalidCode", "invalidReceipt", "serviceNotConfigured", "badgeActive", "storePurchaseOpen", "serviceError", "invalidResponse", "unknownKeyIndex", "credentialNotVerified"]
BadgeServiceErrorCode = Literal["bad_request", "unsupported_version", "unknown_purchase_key", "unknown_offer_id", "offer_disabled", "offer_mismatch", "product_unavailable", "payment_not_entitled", "payment_pending", "provider_unavailable", "provider_not_configured", "rate_limited", "code_invalid", "code_used", "code_expired", "receipt_invalid", "receipt_used", "transfer_limited", "test_purchase", "internal"]
BadgeStatus = Literal["active", "expired", "expiredOld", "failed", "unknownKey"]
BadgeType = Literal["supporter", "legend", "investor"]
class BlockToken_lineBreak(TypedDict):
type: Literal["lineBreak"]
class BlockToken_softBreak(TypedDict):
type: Literal["softBreak"]
class BlockToken_hardBreak(TypedDict):
type: Literal["hardBreak"]
class BlockToken_paragraphBreak(TypedDict):
type: Literal["paragraphBreak"]
lineBreaks: int # int
class BlockToken_indent(TypedDict):
type: Literal["indent"]
class BlockToken_headingMark(TypedDict):
type: Literal["headingMark"]
level: int # int
class BlockToken_headingClose(TypedDict):
type: Literal["headingClose"]
class BlockToken_headingUnderline(TypedDict):
type: Literal["headingUnderline"]
level: int # int
class BlockToken_listMark(TypedDict):
type: Literal["listMark"]
number: NotRequired[str]
class BlockToken_quoteMark(TypedDict):
type: Literal["quoteMark"]
class BlockToken_fenceMark(TypedDict):
type: Literal["fenceMark"]
language: NotRequired[str]
class BlockToken_rowMark(TypedDict):
type: Literal["rowMark"]
class BlockToken_cellMark(TypedDict):
type: Literal["cellMark"]
class BlockToken_delimiterRow(TypedDict):
type: Literal["delimiterRow"]
columns: list["TableAlign"]
class BlockToken_ruleMark(TypedDict):
type: Literal["ruleMark"]
BlockToken = (
BlockToken_lineBreak
| BlockToken_softBreak
| BlockToken_hardBreak
| BlockToken_paragraphBreak
| BlockToken_indent
| BlockToken_headingMark
| BlockToken_headingClose
| BlockToken_headingUnderline
| BlockToken_listMark
| BlockToken_quoteMark
| BlockToken_fenceMark
| BlockToken_rowMark
| BlockToken_cellMark
| BlockToken_delimiterRow
| BlockToken_ruleMark
)
BlockToken_Tag = Literal["lineBreak", "softBreak", "hardBreak", "paragraphBreak", "indent", "headingMark", "headingClose", "headingUnderline", "listMark", "quoteMark", "fenceMark", "rowMark", "cellMark", "delimiterRow", "ruleMark"]
class BlockingInfo(TypedDict):
reason: "BlockingReason"
notice: NotRequired["ClientNotice"]
@@ -670,6 +787,7 @@ class CIQuote(TypedDict):
sentAt: str # ISO-8601 timestamp
content: "MsgContent"
formattedText: NotRequired[list["FormattedText"]]
markdownBlocks: NotRequired[list["MarkdownBlock"]] # non-empty
class CIReaction(TypedDict):
chatDir: "CIDirection"
@@ -1048,6 +1166,10 @@ class ChatErrorType_commandError(TypedDict):
type: Literal["commandError"]
message: str
class ChatErrorType_badgeRedeemError(TypedDict):
type: Literal["badgeRedeemError"]
badgeRedeemError: "BadgeRedeemError"
class ChatErrorType_agentCommandError(TypedDict):
type: Literal["agentCommandError"]
message: str
@@ -1146,6 +1268,7 @@ ChatErrorType = (
| ChatErrorType_agentVersion
| ChatErrorType_agentNoSubResult
| ChatErrorType_commandError
| ChatErrorType_badgeRedeemError
| ChatErrorType_agentCommandError
| ChatErrorType_invalidFileDescription
| ChatErrorType_connectionIncognitoChangeProhibited
@@ -1156,7 +1279,7 @@ ChatErrorType = (
| ChatErrorType_exception
)
ChatErrorType_Tag = Literal["noActiveUser", "noConnectionUser", "noSndFileUser", "noRcvFileUser", "userUnknown", "userExists", "chatRelayExists", "differentActiveUser", "cantDeleteActiveUser", "cantDeleteLastUser", "cantHideLastUser", "hiddenUserAlwaysMuted", "emptyUserPassword", "userAlreadyHidden", "userNotHidden", "invalidDisplayName", "chatNotStarted", "chatNotStopped", "chatStoreChanged", "invalidConnReq", "simplexDomainNotReady", "notResolvedLocally", "unsupportedConnReq", "connReqMessageProhibited", "contactNotReady", "contactNotActive", "contactDisabled", "connectionDisabled", "groupUserRole", "groupMemberInitialRole", "contactIncognitoCantInvite", "groupIncognitoCantInvite", "groupContactRole", "groupDuplicateMember", "groupDuplicateMemberId", "groupNotJoined", "groupMemberNotActive", "cantBlockMemberForSelf", "groupMemberUserRemoved", "groupMemberNotFound", "groupCantResendInvitation", "groupInternal", "fileNotFound", "fileSize", "fileAlreadyReceiving", "fileCancelled", "fileCancel", "fileAlreadyExists", "fileWrite", "fileSend", "fileRcvChunk", "fileInternal", "fileImageType", "fileImageSize", "fileNotReceived", "fileNotApproved", "fallbackToSMPProhibited", "inlineFileProhibited", "invalidForward", "invalidChatItemUpdate", "invalidChatItemDelete", "hasCurrentCall", "noCurrentCall", "callContact", "directMessagesProhibited", "agentVersion", "agentNoSubResult", "commandError", "agentCommandError", "invalidFileDescription", "connectionIncognitoChangeProhibited", "connectionUserChangeProhibited", "peerChatVRangeIncompatible", "relayTestError", "internalError", "exception"]
ChatErrorType_Tag = Literal["noActiveUser", "noConnectionUser", "noSndFileUser", "noRcvFileUser", "userUnknown", "userExists", "chatRelayExists", "differentActiveUser", "cantDeleteActiveUser", "cantDeleteLastUser", "cantHideLastUser", "hiddenUserAlwaysMuted", "emptyUserPassword", "userAlreadyHidden", "userNotHidden", "invalidDisplayName", "chatNotStarted", "chatNotStopped", "chatStoreChanged", "invalidConnReq", "simplexDomainNotReady", "notResolvedLocally", "unsupportedConnReq", "connReqMessageProhibited", "contactNotReady", "contactNotActive", "contactDisabled", "connectionDisabled", "groupUserRole", "groupMemberInitialRole", "contactIncognitoCantInvite", "groupIncognitoCantInvite", "groupContactRole", "groupDuplicateMember", "groupDuplicateMemberId", "groupNotJoined", "groupMemberNotActive", "cantBlockMemberForSelf", "groupMemberUserRemoved", "groupMemberNotFound", "groupCantResendInvitation", "groupInternal", "fileNotFound", "fileSize", "fileAlreadyReceiving", "fileCancelled", "fileCancel", "fileAlreadyExists", "fileWrite", "fileSend", "fileRcvChunk", "fileInternal", "fileImageType", "fileImageSize", "fileNotReceived", "fileNotApproved", "fallbackToSMPProhibited", "inlineFileProhibited", "invalidForward", "invalidChatItemUpdate", "invalidChatItemDelete", "hasCurrentCall", "noCurrentCall", "callContact", "directMessagesProhibited", "agentVersion", "agentNoSubResult", "commandError", "badgeRedeemError", "agentCommandError", "invalidFileDescription", "connectionIncognitoChangeProhibited", "connectionUserChangeProhibited", "peerChatVRangeIncompatible", "relayTestError", "internalError", "exception"]
ChatFeature = Literal["timedMessages", "fullDelete", "reactions", "voice", "files", "calls", "sessions"]
@@ -1202,6 +1325,7 @@ class ChatItem(TypedDict):
content: "CIContent"
mentions: dict[str, "CIMention"]
formattedText: NotRequired[list["FormattedText"]]
markdownBlocks: NotRequired[list["MarkdownBlock"]] # non-empty
quotedItem: NotRequired["CIQuote"]
reactions: list["CIReactionCount"]
file: NotRequired["CIFile"]
@@ -1212,6 +1336,22 @@ class ChatItemDeletion(TypedDict):
deletedChatItem: "AChatItem"
toChatItem: NotRequired["AChatItem"]
class ChatItemInfo(TypedDict):
itemVersions: list["ChatItemVersion"]
memberDeliveryStatuses: NotRequired[list["MemberDeliveryStatus"]] # non-empty
forwardedFromChatItem: NotRequired["AChatItem"]
fileXftpServers: list[str]
class ChatItemVersion(TypedDict):
chatItemVersionId: int # int64
msgContent: "MsgContent"
formattedText: NotRequired[list["FormattedText"]]
markdownBlocks: NotRequired[list["MarkdownBlock"]] # non-empty
itemVersionTs: str # ISO-8601 timestamp
createdAt: str # ISO-8601 timestamp
ChatLayout = Literal["classic", "terminal"]
class ChatListQuery_filters(TypedDict):
type: Literal["filters"]
favorite: bool
@@ -1225,7 +1365,44 @@ ChatListQuery = ChatListQuery_filters | ChatListQuery_search
ChatListQuery_Tag = Literal["filters", "search"]
ChatPeerType = Literal["human", "bot", "business"]
class ChatPagination_last(TypedDict):
type: Literal["last"]
count: int # int
class ChatPagination_after(TypedDict):
type: Literal["after"]
chatItemId: int # int64
count: int # int
class ChatPagination_before(TypedDict):
type: Literal["before"]
chatItemId: int # int64
count: int # int
class ChatPagination_around(TypedDict):
type: Literal["around"]
chatItemId: int # int64
count: int # int
class ChatPagination_initial(TypedDict):
type: Literal["initial"]
count: int # int
ChatPagination = (
ChatPagination_last
| ChatPagination_after
| ChatPagination_before
| ChatPagination_around
| ChatPagination_initial
)
ChatPagination_Tag = Literal["last", "after", "before", "around", "initial"]
def ChatPagination_cmd_string(self: ChatPagination) -> str:
return 'count=' + str(self['count']) if str(self['type']) == 'last' else 'after=' + str(self['chatItemId']) + ' count=' + str(self['count']) if str(self['type']) == 'after' else 'before=' + str(self['chatItemId']) + ' count=' + str(self['count']) if str(self['type']) == 'before' else 'around=' + str(self['chatItemId']) + ' count=' + str(self['count']) if str(self['type']) == 'around' else 'initial=' + str(self['count']) # type: ignore[typeddict-item]
ChatPeerType = Literal["human", "bot", "business", "agent"]
# Used in API commands. Chat scope can only be passed with groups.
@@ -1336,6 +1513,19 @@ class ComposedMessage(TypedDict):
msgContent: "MsgContent"
mentions: dict[str, int] # str : int64
class ConditionsAcceptance_accepted(TypedDict):
type: Literal["accepted"]
acceptedAt: NotRequired[str] # ISO-8601 timestamp
autoAccepted: bool
class ConditionsAcceptance_required(TypedDict):
type: Literal["required"]
deadline: NotRequired[str] # ISO-8601 timestamp
ConditionsAcceptance = ConditionsAcceptance_accepted | ConditionsAcceptance_required
ConditionsAcceptance_Tag = Literal["accepted", "required"]
class ConnStatus_new(TypedDict):
type: Literal["new"]
@@ -1482,6 +1672,14 @@ ConnectionPlan = (
ConnectionPlan_Tag = Literal["invitationLink", "contactAddress", "groupLink", "error"]
class ConnectionStats(TypedDict):
connAgentVersion: int # int
rcvQueuesInfo: list["RcvQueueInfo"]
sndQueuesInfo: list["SndQueueInfo"]
ratchetSyncState: "RatchetSyncState"
ratchetSyncSupported: bool
subStatus: NotRequired["SubscriptionStatus"]
class Contact(TypedDict):
contactId: int # int64
localDisplayName: str
@@ -1504,6 +1702,7 @@ class Contact(TypedDict):
chatTags: list[int] # int64
chatItemTTL: NotRequired[int] # int64
uiThemes: NotRequired["UIThemeEntityOverrides"]
chatLayout: NotRequired["ChatLayout"]
chatDeleted: bool
customData: NotRequired[dict[str, object]]
@@ -1545,6 +1744,7 @@ class ContactShortLinkData(TypedDict):
profile: "Profile"
message: NotRequired["MsgContent"]
business: bool
chatLayout: NotRequired["ChatLayout"]
localBadge: NotRequired["LocalBadge"]
ContactStatus = Literal["active", "deleted", "deletedByUser", "rejected"]
@@ -1785,8 +1985,11 @@ class FileTransferMeta(TypedDict):
FileType = Literal["normal", "roster"]
# The format markup is a token of block Markdown syntax; its text is the syntax. The format escape is the backslash of a backslash escape. Bold singleStar: written with single stars.
class Format_bold(TypedDict):
type: Literal["bold"]
singleStar: bool
class Format_italic(TypedDict):
type: Literal["italic"]
@@ -1840,6 +2043,13 @@ class Format_email(TypedDict):
class Format_phone(TypedDict):
type: Literal["phone"]
class Format_escape(TypedDict):
type: Literal["escape"]
class Format_markup(TypedDict):
type: Literal["markup"]
token: "BlockToken"
Format = (
Format_bold
| Format_italic
@@ -1856,9 +2066,11 @@ Format = (
| Format_mention
| Format_email
| Format_phone
| Format_escape
| Format_markup
)
Format_Tag = Literal["bold", "italic", "strikeThrough", "snippet", "secret", "small", "colored", "uri", "hyperLink", "simplexLink", "simplexName", "command", "mention", "email", "phone"]
Format_Tag = Literal["bold", "italic", "strikeThrough", "snippet", "secret", "small", "colored", "uri", "hyperLink", "simplexLink", "simplexName", "command", "mention", "email", "phone", "escape", "markup"]
class FormattedText(TypedDict):
format: NotRequired["Format"]
@@ -1949,13 +2161,8 @@ class GroupInfo(TypedDict):
rosterVersion: NotRequired[int] # int64
membersRequireAttention: int # int
viaGroupLinkUri: NotRequired[str]
groupKeys: NotRequired["GroupKeys"]
groupDomainVerified: NotRequired[bool]
class GroupKeys(TypedDict):
publicGroupKeys: NotRequired["PublicGroupKeys"]
memberPrivKey: str
class GroupLink(TypedDict):
userContactLinkId: int # int64
connLinkContact: "CreatedConnLink"
@@ -2053,6 +2260,14 @@ class GroupMemberSettings(TypedDict):
GroupMemberStatus = Literal["rejected", "removed", "left", "deleted", "unknown", "invited", "pending_approval", "pending_review", "introduced", "intro-inv", "accepted", "announced", "connected", "complete", "creator"]
class GroupOwnerContact(TypedDict):
contactId: int # int64
memberId: str
def GroupOwnerContact_cmd_string(self: GroupOwnerContact) -> str:
return 'contact=' + str(self['contactId']) + ' owner=' + self['memberId']
class GroupPreference(TypedDict):
enable: "GroupFeatureEnabled"
@@ -2081,6 +2296,7 @@ class GroupProfile(TypedDict):
publicGroup: NotRequired["PublicGroupProfile"]
groupPreferences: NotRequired["GroupPreferences"]
memberAdmission: NotRequired["GroupMemberAdmission"]
chatLayout: NotRequired["ChatLayout"]
class GroupRelay(TypedDict):
groupRelayId: int # int64
@@ -2090,18 +2306,6 @@ class GroupRelay(TypedDict):
relayLink: NotRequired[str]
relayCap: "RelayCapabilities"
class GroupRootKey_private(TypedDict):
type: Literal["private"]
rootPrivKey: str
class GroupRootKey_public(TypedDict):
type: Literal["public"]
rootPubKey: str
GroupRootKey = GroupRootKey_private | GroupRootKey_public
GroupRootKey_Tag = Literal["private", "public"]
class GroupShortLinkData(TypedDict):
groupProfile: "GroupProfile"
publicGroupData: NotRequired["PublicGroupData"]
@@ -2111,6 +2315,47 @@ class GroupShortLinkInfo(TypedDict):
groupRelays: list[str]
publicGroupId: NotRequired[str]
class GroupSndStatus_new(TypedDict):
type: Literal["new"]
class GroupSndStatus_forwarded(TypedDict):
type: Literal["forwarded"]
class GroupSndStatus_inactive(TypedDict):
type: Literal["inactive"]
class GroupSndStatus_sent(TypedDict):
type: Literal["sent"]
class GroupSndStatus_rcvd(TypedDict):
type: Literal["rcvd"]
msgRcptStatus: "MsgReceiptStatus"
class GroupSndStatus_error(TypedDict):
type: Literal["error"]
agentError: "SndError"
class GroupSndStatus_warning(TypedDict):
type: Literal["warning"]
agentError: "SndError"
class GroupSndStatus_invalid(TypedDict):
type: Literal["invalid"]
text: str
GroupSndStatus = (
GroupSndStatus_new
| GroupSndStatus_forwarded
| GroupSndStatus_inactive
| GroupSndStatus_sent
| GroupSndStatus_rcvd
| GroupSndStatus_error
| GroupSndStatus_warning
| GroupSndStatus_invalid
)
GroupSndStatus_Tag = Literal["new", "forwarded", "inactive", "sent", "rcvd", "error", "warning", "invalid"]
class GroupSummary(TypedDict):
currentMembers: int # int64
publicMemberCount: NotRequired[int] # int64
@@ -2126,6 +2371,8 @@ GroupType = Literal["channel", "group"]
HandshakeError = Literal["PARSE", "IDENTITY", "BAD_AUTH", "BAD_SERVICE"]
HostMode = Literal["onionViaSocks", "onion", "public"]
InlineFileMode = Literal["offer", "sent"]
class InvitationLinkPlan_ok(TypedDict):
@@ -2167,6 +2414,11 @@ InvitedBy = InvitedBy_contact | InvitedBy_user | InvitedBy_unknown
InvitedBy_Tag = Literal["contact", "user", "unknown"]
class KeepAliveOpts(TypedDict):
keepIdle: int # int
keepIntvl: int # int
keepCnt: int # int
class LinkContent_page(TypedDict):
type: Literal["page"]
@@ -2198,6 +2450,11 @@ class LinkPreview(TypedDict):
image: str
content: NotRequired["LinkContent"]
class ListEntry(TypedDict):
number: NotRequired[str]
content: "SegmentRange"
items: list["ListEntry"]
class LocalBadge(TypedDict):
badge: "BadgeInfo"
status: "BadgeStatus"
@@ -2217,8 +2474,57 @@ class LocalProfile(TypedDict):
contactDomain: NotRequired["SimplexDomainClaim"]
contactDomainVerified: NotRequired[bool]
class MarkdownBlock_paragraph(TypedDict):
type: Literal["paragraph"]
content: "SegmentRange"
class MarkdownBlock_heading(TypedDict):
type: Literal["heading"]
level: int # int
content: "SegmentRange"
class MarkdownBlock_codeBlock(TypedDict):
type: Literal["codeBlock"]
language: NotRequired[str]
content: "SegmentRange"
class MarkdownBlock_quote(TypedDict):
type: Literal["quote"]
content: "SegmentRange"
class MarkdownBlock_list(TypedDict):
type: Literal["list"]
items: list["ListEntry"] # non-empty
class MarkdownBlock_table(TypedDict):
type: Literal["table"]
columns: list["TableAlign"] # non-empty
header: list["SegmentRange"]
rows: list[list["SegmentRange"]]
class MarkdownBlock_rule(TypedDict):
type: Literal["rule"]
mark: "SegmentRange"
MarkdownBlock = (
MarkdownBlock_paragraph
| MarkdownBlock_heading
| MarkdownBlock_codeBlock
| MarkdownBlock_quote
| MarkdownBlock_list
| MarkdownBlock_table
| MarkdownBlock_rule
)
MarkdownBlock_Tag = Literal["paragraph", "heading", "codeBlock", "quote", "list", "table", "rule"]
MemberCriteria = Literal["all"]
class MemberDeliveryStatus(TypedDict):
groupMemberId: int # int64
memberDeliveryStatus: "GroupSndStatus"
sentViaProxy: NotRequired[bool]
# Connection link sent in a message - only short links are allowed.
class MsgChatLink_contact(TypedDict):
@@ -2301,6 +2607,8 @@ MsgContent = (
MsgContent_Tag = Literal["text", "link", "image", "video", "voice", "file", "report", "chat", "unknown"]
MsgContentTag = Literal["text", "link", "image", "video", "voice", "file", "report", "chat"]
MsgDecryptError = Literal["ratchetHeader", "tooManySkipped", "ratchetEarlier", "other", "ratchetSync"]
MsgDirection = Literal["rcv", "snd"]
@@ -2373,6 +2681,28 @@ NameErrorType = NameErrorType_NO_RESOLVER | NameErrorType_NOT_FOUND | NameErrorT
NameErrorType_Tag = Literal["NO_RESOLVER", "NOT_FOUND", "RESOLVER"]
class NavigationInfo(TypedDict):
afterUnread: int # int
afterTotal: int # int
class NetworkConfig(TypedDict):
socksProxy: NotRequired[str]
socksMode: "SocksMode"
hostMode: "HostMode"
requiredHostMode: bool
sessionMode: "TransportSessionMode"
smpProxyMode: "SMPProxyMode"
smpProxyFallback: "SMPProxyFallback"
smpWebPortServers: "SMPWebPortServers"
tcpConnectTimeout: "NetworkTimeout"
tcpTimeout: "NetworkTimeout"
tcpTimeoutPerKb: int # int64
rcvConcurrency: int # int
tcpKeepAlive: NotRequired["KeepAliveOpts"]
smpPingInterval: int # int64
smpPingCount: int # int
logTLSErrors: bool
class NetworkError_connectError(TypedDict):
type: Literal["connectError"]
connectError: str
@@ -2405,6 +2735,10 @@ NetworkError = (
NetworkError_Tag = Literal["connectError", "tLSError", "unknownCAError", "failedError", "timeoutError", "subscribeError"]
class NetworkTimeout(TypedDict):
backgroundTimeout: int # int
interactiveTimeout: int # int
class NewUser(TypedDict):
profile: NotRequired["Profile"]
pastTimestamp: bool
@@ -2420,6 +2754,8 @@ class NoteFolder(TypedDict):
favorite: bool
unread: bool
OperatorTag = Literal["simplex", "flux"]
class OwnerVerification_verified(TypedDict):
type: Literal["verified"]
@@ -2458,6 +2794,10 @@ class PendingContactConnection(TypedDict):
PlanResolveMode = Literal["allGroups", "unknown", "never"]
def PlanResolveMode_cmd_string(self: PlanResolveMode) -> str:
return ' resolve=allGroups' if str(self) == 'allGroups' else ' resolve=never' if str(self) == 'never' else ''
class PrefEnabled(TypedDict):
forUser: bool
forContact: bool
@@ -2544,16 +2884,14 @@ class PublicGroupAccess(TypedDict):
class PublicGroupData(TypedDict):
publicMemberCount: int # int64
class PublicGroupKeys(TypedDict):
publicGroupId: str
groupRootKey: "GroupRootKey"
class PublicGroupProfile(TypedDict):
groupType: "GroupType"
groupLink: str
publicGroupId: str
publicGroupAccess: NotRequired["PublicGroupAccess"]
QueueStatus = Literal["new", "confirmed", "secured", "active", "disabled"]
class RCErrorType_internal(TypedDict):
type: Literal["internal"]
internalErr: str
@@ -2823,6 +3161,15 @@ RcvMsgError = RcvMsgError_dropped | RcvMsgError_parseError
RcvMsgError_Tag = Literal["dropped", "parseError"]
class RcvQueueInfo(TypedDict):
rcvServer: str
status: "QueueStatus"
rcvSwitchStatus: NotRequired["RcvSwitchStatus"]
canAbortSwitch: bool
subStatus: "SubscriptionStatus"
RcvSwitchStatus = Literal["switch_started", "sending_qadd", "sending_quse", "received_message", "received_qend"]
class RelayCapabilities(TypedDict):
webDomain: NotRequired[str]
@@ -2944,10 +3291,42 @@ SMPAgentError = (
SMPAgentError_Tag = Literal["A_MESSAGE", "A_PROHIBITED", "A_VERSION", "A_LINK", "A_CRYPTO", "A_DUPLICATE", "A_QUEUE", "A_SERVICE"]
SMPProxyFallback = Literal["allow", "allowProtected", "prohibit"]
SMPProxyMode = Literal["always", "unknown", "unprotected", "never"]
SMPWebPortServers = Literal["all", "preset", "off"]
class SecurityCode(TypedDict):
securityCode: str
verifiedAt: str # ISO-8601 timestamp
SegmentRange = TypedDict("SegmentRange", {
"from": int, # int
"to": int, # int
})
class ServerOperator(TypedDict):
operatorId: int # int64
operatorTag: NotRequired["OperatorTag"]
tradeName: str
legalName: NotRequired[str]
serverDomains: list[str]
conditionsAcceptance: "ConditionsAcceptance"
enabled: bool
smpRoles: "ServerRoles"
xftpRoles: "ServerRoles"
class ServerRoles(TypedDict):
storage: bool
proxy: bool
names: bool
class ServerRolesOverride(TypedDict):
storage: NotRequired[bool]
proxy: NotRequired[bool]
names: NotRequired[bool]
class SimplePreference(TypedDict):
allow: "FeatureAllowed"
@@ -3107,6 +3486,15 @@ SndGroupEvent = (
SndGroupEvent_Tag = Literal["memberRole", "memberBlocked", "userRole", "memberDeleted", "userLeft", "groupUpdated", "memberAccepted", "userPendingReview"]
class SndQueueInfo(TypedDict):
sndServer: str
status: "QueueStatus"
sndSwitchStatus: NotRequired["SndSwitchStatus"]
SndSwitchStatus = Literal["sending_qkey", "sending_qtest", "securing_queue", "sending_qend"]
SocksMode = Literal["always", "onion"]
class SrvError_host(TypedDict):
type: Literal["host"]
@@ -3608,6 +3996,8 @@ class SupportGroupPreference(TypedDict):
SwitchPhase = Literal["started", "confirmed", "secured", "completed"]
TableAlign = Literal["none", "left", "center", "right"]
class TimedMessagesGroupPreference(TypedDict):
enable: "GroupFeatureEnabled"
ttl: NotRequired[int] # int
@@ -3646,6 +4036,8 @@ TransportError = (
TransportError_Tag = Literal["badBlock", "version", "largeMsg", "badSession", "noServerAuth", "handshake"]
TransportSessionMode = Literal["user", "session", "server", "entity"]
UIColorMode = Literal["light", "dark"]
class UIColors(TypedDict):
@@ -3670,6 +4062,7 @@ class UIThemeEntityOverride(TypedDict):
class UIThemeEntityOverrides(TypedDict):
light: NotRequired["UIThemeEntityOverride"]
dark: NotRequired["UIThemeEntityOverride"]
chatLayout: NotRequired["ChatLayout"]
class UpdatedMessage(TypedDict):
msgContent: "MsgContent"
@@ -3743,6 +4136,12 @@ class UserInfo(TypedDict):
user: "User"
unreadCount: int # int
class UserOperatorServers(TypedDict):
operator: NotRequired["ServerOperator"]
smpServers: list["UserServer"]
xftpServers: list["UserServer"]
chatRelays: list["UserChatRelay"]
class UserProfileUpdateSummary(TypedDict):
updateSuccesses: int # int
updateFailures: int # int
@@ -3752,6 +4151,15 @@ class UserPwdHash(TypedDict):
hash: str
salt: str
class UserServer(TypedDict):
serverId: int # int64
server: str
preset: bool
tested: NotRequired[bool]
enabled: bool
roles: "ServerRolesOverride"
deleted: bool
class VersionRange(TypedDict):
minVersion: int # int
maxVersion: int # int
@@ -101,7 +101,7 @@ def ci_content_text(chat_item: T.ChatItem) -> str | None:
return None
_BOT_COMMAND_RE = re.compile(r"^/([^\s]+)(.*)$")
_BOT_COMMAND_RE = re.compile(r"^/([^\s]+)(.*)$", re.DOTALL)
def ci_bot_command(chat_item: T.ChatItem) -> tuple[str, str] | None:
@@ -7,6 +7,7 @@ shape it accepts.
from __future__ import annotations
import asyncio
from typing import Any
import pytest
@@ -172,3 +173,46 @@ async def test_a_failed_custom_data_write_raises():
api = FakeCtrl({"type": "chatCmdError"})
with pytest.raises(ChatCommandError):
await api.api_merge_group_custom_data({"groupId": 9}, "mine", 1)
# ---------------------------------------------------------------------- #
# Documented success responses
# ---------------------------------------------------------------------- #
def test_update_chat_item_accepts_not_changed():
chat_item = {"meta": {"itemId": 2}}
api = FakeCtrl({"type": "chatItemNotChanged", "chatItem": {"chatItem": chat_item}})
msg_content = {"type": "text", "text": "same"}
assert asyncio.run(api.api_update_chat_item("direct", 1, 2, msg_content)) == chat_item
def test_set_profile_address_accepts_no_change():
api = FakeCtrl({"type": "userProfileNoChange"})
summary = asyncio.run(api.api_set_profile_address(1, True))
assert summary == {"updateSuccesses": 0, "updateFailures": 0, "changedContacts": []}
def test_receive_file_reports_cancelled_by_sender():
api = FakeCtrl({"type": "rcvFileAcceptedSndCancelled", "rcvFileTransfer": {}})
with pytest.raises(ChatCommandError, match="file cancelled by sender"):
asyncio.run(api.api_receive_file(3))
async def test_init_loads_library_off_the_event_loop(monkeypatch):
import threading
from simplex_chat import _native, core
from simplex_chat.api import SqliteDb
threads: list[int] = []
monkeypatch.setattr(_native, "lib_for", lambda _backend: threads.append(threading.get_ident()))
async def fake_migrate_init(*_args):
return 1
monkeypatch.setattr(core, "chat_migrate_init", fake_migrate_init)
loop_thread = threading.get_ident()
await ChatApi.init(SqliteDb(file_prefix="/tmp/unused"))
assert threads and threads[0] != loop_thread
@@ -14,11 +14,13 @@ import pytest
from simplex_chat import (
Bot,
BotProfile,
ChatCommandError,
Client,
ContactAlreadyExistsError,
Profile,
SqliteDb,
)
from simplex_chat.core import MigrationConfirmation
class FakeApi:
@@ -292,6 +294,31 @@ def test_send_and_wait_parallel_different_contacts():
assert (a, b) == ("A", "B")
def test_send_and_wait_keeps_waiter_registered_during_previous_cleanup():
bot, _api = _bot_with_fake_api()
def reply(text: str) -> dict[str, Any]:
return {"type": "newChatItems", "chatItems": [
{
"chatInfo": {"type": "direct", "contact": {"contactId": 42}},
"chatItem": {"content": {"type": "rcvMsgContent", "msgContent": {"type": "text", "text": text}}},
}
]}
async def go() -> tuple[str, str]:
first = asyncio.create_task(bot.send_and_wait(42, "a", timeout=2.0))
await asyncio.sleep(0)
# Created before the reply is dispatched, so it registers before `first` runs its cleanup.
second = asyncio.create_task(bot.send_and_wait(42, "b", timeout=2.0))
await bot._dispatch_event(reply("ra")) # type: ignore[arg-type]
await asyncio.sleep(0)
await asyncio.sleep(0)
await bot._dispatch_event(reply("rb")) # type: ignore[arg-type]
return (await first).text or "", (await second).text or ""
assert asyncio.run(go()) == ("ra", "rb")
# ---------------------------------------------------------------------------
# connect_to
# ---------------------------------------------------------------------------
@@ -466,6 +493,10 @@ def test_aexit_nulls_api_even_if_close_raises(monkeypatch):
async def stop_chat(self):
pass
@property
def initialized(self):
return False
async def close(self):
raise RuntimeError("close failed")
@@ -498,6 +529,83 @@ def test_aexit_nulls_api_even_if_close_raises(monkeypatch):
asyncio.run(go())
def test_aexit_keeps_api_for_retry_when_stop_fails(monkeypatch):
"""A failed stop leaves the store open, so the Client must keep the
controller: dropping it would leak the store with no way to close it."""
import simplex_chat.client as client_mod
stop_results = ["chatCmdError", "chatStopped"]
closed: list[bool] = [False]
class _FailingStopApi:
@classmethod
async def init(cls, *_a, **_kw):
return cls()
@property
def initialized(self):
return not closed[0]
async def start_chat(self):
pass
async def close(self):
response = stop_results.pop(0)
if response != "chatStopped":
raise ChatCommandError("error stopping chat", {"type": response})
closed[0] = True
async def api_get_active_user(self):
return {"userId": 1, "profile": {"displayName": "x"}}
async def send_chat_cmd(self, _cmd):
return {"type": "cmdOk"}
monkeypatch.setattr(client_mod, "ChatApi", _FailingStopApi)
c = Client(profile=Profile(display_name="x"), db=SqliteDb(file_prefix="/tmp/test"))
async def go():
with pytest.raises(ChatCommandError, match="error stopping chat"):
async with c:
pass
assert c._api is not None, "controller dropped while its store is still open"
assert closed == [False]
await c.__aexit__(None, None, None)
assert closed == [True]
assert c._api is None
asyncio.run(go())
@pytest.mark.parametrize("queue_size", [None, 65536])
def test_bot_passes_queue_size_to_chat_api_init(monkeypatch, queue_size):
import simplex_chat.client as client_mod
init_args: list[tuple[Any, ...]] = []
class StopInit(RuntimeError):
pass
class FakeChatApi:
@classmethod
async def init(cls, *args):
init_args.append(args)
raise StopInit
monkeypatch.setattr(client_mod, "ChatApi", FakeChatApi)
db = SqliteDb(file_prefix="/tmp/test")
bot = Bot(profile=BotProfile(display_name="x"), db=db, queue_size=queue_size)
async def go():
with pytest.raises(StopInit):
async with bot:
pytest.fail("should not enter the with-block")
asyncio.run(go())
assert init_args == [(db, MigrationConfirmation.YES_UP, queue_size)]
def test_aenter_rolls_back_partial_init_on_post_start_failure(monkeypatch):
"""If anything in __aenter__ raises after ChatApi.init succeeded — including
_post_start — the controller must be closed. Otherwise the with-block isn't
@@ -550,7 +658,7 @@ def test_aenter_rolls_back_partial_init_on_post_start_failure(monkeypatch):
pytest.fail("should not enter the with-block")
asyncio.run(go())
assert closed == ["stop", "close"], f"controller not cleaned up: {closed}"
assert closed == ["close"], f"controller not cleaned up: {closed}"
assert c._api is None, "Client._api should be reset to None after rollback"
@@ -621,6 +729,7 @@ class _StubApi:
def __init__(self) -> None:
self.profiles: list[dict] = []
self.address_settings: list[dict] = []
self.user: dict = {"userId": 1, "profile": {"displayName": "x", "fullName": ""}}
self.address: dict | None = None
@@ -650,8 +759,8 @@ class _StubApi:
async def api_get_user_address(self, _user_id):
return self.address
async def api_set_address_settings(self, _user_id, _settings):
pass
async def api_set_address_settings(self, _user_id, settings):
self.address_settings.append(settings)
async def send_chat_cmd(self, _cmd):
return {"type": "cmdOk"}
@@ -834,6 +943,55 @@ def test_sync_profile_keeps_the_bot_address_in_the_profile(monkeypatch):
assert api.profiles[0]["contactLink"] == "https://l"
def test_bot_address_settings_include_the_chat_layout(monkeypatch):
import simplex_chat.client as client_mod
api = _StubApi()
api.address = {
"connLinkContact": {"connFullLink": "https://l"},
"addressSettings": {"businessAddress": False, "autoAccept": {"acceptIncognito": False}},
}
monkeypatch.setattr(client_mod, "ChatApi", _init_returning(api))
bot = Bot(
profile=BotProfile(display_name="x"),
db=SqliteDb(file_prefix="/tmp/test"),
update_profile=False,
chat_layout="terminal",
)
async def go():
async with bot:
pass
asyncio.run(go())
assert api.address_settings == [
{"businessAddress": False, "autoAccept": {"acceptIncognito": False}, "chatLayout": "terminal"}
]
def test_bot_address_settings_remove_the_chat_layout_not_in_bot_settings(monkeypatch):
import simplex_chat.client as client_mod
api = _StubApi()
api.address = {
"connLinkContact": {"connFullLink": "https://l"},
"addressSettings": {"businessAddress": False, "chatLayout": "terminal"},
}
monkeypatch.setattr(client_mod, "ChatApi", _init_returning(api))
bot = Bot(
profile=BotProfile(display_name="x"),
db=SqliteDb(file_prefix="/tmp/test"),
update_profile=False,
)
async def go():
async with bot:
pass
asyncio.run(go())
assert api.address_settings == [{"businessAddress": False, "autoAccept": {"acceptIncognito": False}}]
def test_profile_can_be_replaced(monkeypatch):
c, _ = _client_with_stub_api(monkeypatch)
c.profile = Profile(display_name="other", full_name="Other")
@@ -39,3 +39,108 @@ def test_chat_ref_cmd_string_direct():
"""Sanity check the codegen fix for ChatRef-bearing commands."""
assert T.ChatRef_cmd_string({"chatType": "direct", "chatId": 7}) == "@7"
assert T.ChatRef_cmd_string({"chatType": "group", "chatId": 42}) == "#42"
def test_api_connect_cmd_string_renders_incognito():
link = {"connFullLink": "L"}
assert CC.APIConnect_cmd_string({"userId": 1, "incognito": True, "preparedLink_": link}) == "/_connect 1 incognito=on L"
assert CC.APIConnect_cmd_string({"userId": 1, "incognito": False, "preparedLink_": link}) == "/_connect 1 L"
def test_chat_pagination_cmd_string():
assert T.ChatPagination_cmd_string({"type": "last", "count": 0}) == "count=0"
assert T.ChatPagination_cmd_string({"type": "initial", "count": 1}) == "initial=1"
assert (
T.ChatPagination_cmd_string({"type": "around", "chatItemId": 5, "count": 0})
== "around=5 count=0"
)
assert (
T.ChatPagination_cmd_string({"type": "after", "chatItemId": 5, "count": 100})
== "after=5 count=100"
)
assert (
T.ChatPagination_cmd_string({"type": "before", "chatItemId": 5, "count": 10})
== "before=5 count=10"
)
def test_api_get_chat_cmd_string():
ref = {"chatType": "direct", "chatId": 2}
last = {"type": "last", "count": 10}
assert (
CC.APIGetChat_cmd_string(
{"chatRef": ref, "contentTag": "image", "chatPagination": last, "search": "k"}
)
== "/_get chat @2 content=image count=10 search=k"
)
assert (
CC.APIGetChat_cmd_string(
{"chatRef": ref, "chatPagination": {"type": "initial", "count": 1}}
)
== "/_get chat @2 initial=1"
)
def test_api_chat_items_read_cmd_string():
ref = {"chatType": "direct", "chatId": 2}
assert (
CC.APIChatItemsRead_cmd_string({"chatRef": ref, "chatItemIds": [3, 4]})
== "/_read chat items @2 3,4"
)
def test_api_connect_plan_cmd_string_omits_default_resolve_mode():
assert T.PlanResolveMode_cmd_string("unknown") == ""
assert T.PlanResolveMode_cmd_string("allGroups") == " resolve=allGroups"
assert T.PlanResolveMode_cmd_string("never") == " resolve=never"
assert (
CC.APIConnectPlan_cmd_string({"userId": 1, "connectTarget": "L", "resolveMode": "unknown"})
== "/_connect plan 1 L"
)
assert (
CC.APIConnectPlan_cmd_string({"userId": 1, "connectTarget": "L", "resolveMode": "never"})
== "/_connect plan 1 L resolve=never"
)
def test_api_connect_prepared_group_cmd_string():
owner = {"contactId": 1, "memberId": "abc"}
msg = {"type": "text", "text": "hi"}
assert T.GroupOwnerContact_cmd_string(owner) == "contact=1 owner=abc"
assert (
CC.APIConnectPreparedGroup_cmd_string(
{"groupId": 3, "incognito": False, "ownerContact": owner}
)
== "/_connect group #3 contact=1 owner=abc"
)
assert (
CC.APIConnectPreparedGroup_cmd_string({"groupId": 3, "incognito": True, "msgContent_": msg})
== '/_connect group #3 incognito=on json {"type": "text", "text": "hi"}'
)
def test_member_contact_cmd_string():
assert (
CC.APICreateMemberContact_cmd_string({"groupId": 1, "groupMemberId": 2})
== "/_create member contact #1 2"
)
assert (
CC.APISendMemberContactInvitation_cmd_string({"contactId": 2})
== "/_invite member contact @2"
)
def test_api_get_network_config_cmd_string():
assert CC.APIGetNetworkConfig_cmd_string({}) == "/network"
def test_api_get_chat_item_info_cmd_string():
ref = {"chatType": "direct", "chatId": 2}
assert (
CC.APIGetChatItemInfo_cmd_string({"chatRef": ref, "chatItemId": 5})
== "/_get item info @2 5"
)
def test_api_get_user_servers_cmd_string():
assert CC.APIGetUserServers_cmd_string({"userId": 1}) == "/_servers 1"
@@ -0,0 +1,123 @@
"""core.chat_migrate_init picks the FFI export by queue_size, with a fake libsimplex."""
from __future__ import annotations
import asyncio
import json
from typing import Any
import pytest
from simplex_chat import core
from simplex_chat.core import ChatInitError, MigrationConfirmation
CTRL = 42
class FakeLib:
"""Records calls; each export writes CTRL to the out-param and returns the JSON result."""
def __init__(self, result: dict[str, Any]) -> None:
self.result = json.dumps(result)
self.calls: list[tuple[str, tuple[Any, ...]]] = []
def _init(self, name: str, args: tuple[Any, ...]) -> str:
*call_args, ctrl_ref = args
self.calls.append((name, tuple(call_args)))
ctrl_ref._obj.value = CTRL
return self.result
def chat_migrate_init(self, *args: Any) -> str:
return self._init("chat_migrate_init", args)
@property
def chat_migrate_init_queue(self) -> Any:
lib = self
class Fn:
argtypes: Any = None
restype: Any = None
def __call__(self, *args: Any) -> str:
return lib._init("chat_migrate_init_queue", args)
return Fn()
class OldLib(FakeLib):
"""A libsimplex released before chat_migrate_init_queue existed."""
def __getattribute__(self, name: str) -> Any:
if name == "chat_migrate_init_queue":
raise AttributeError(name)
return super().__getattribute__(name)
@pytest.fixture
def fake_lib(monkeypatch: pytest.MonkeyPatch):
def install(result: dict[str, Any]) -> FakeLib:
lib = FakeLib(result)
monkeypatch.setattr(core._native, "lib", lambda: lib)
monkeypatch.setattr(core, "_read_and_free", lambda ptr: ptr)
return lib
return install
def migrate_init(queue_size: int | None = None) -> int:
return asyncio.run(
core.chat_migrate_init("/tmp/db", "key", MigrationConfirmation.YES_UP, queue_size)
)
def test_without_queue_size_uses_chat_migrate_init(fake_lib):
lib = fake_lib({"type": "ok"})
assert migrate_init() == CTRL
assert lib.calls == [("chat_migrate_init", (b"/tmp/db", b"key", b"yesUp"))]
def test_with_queue_size_uses_chat_migrate_init_queue(fake_lib):
lib = fake_lib({"type": "ok"})
assert migrate_init(65536) == CTRL
assert lib.calls == [("chat_migrate_init_queue", (b"/tmp/db", b"key", b"yesUp", 65536))]
def test_invalid_queue_size_result_raises_init_error(fake_lib):
fake_lib({"type": "invalidQueueSize"})
with pytest.raises(ChatInitError) as e:
migrate_init(0)
assert e.value.db_migration_error == {"type": "invalidQueueSize"}
@pytest.mark.parametrize("queue_size", [2**31, -(2**31) - 1])
def test_queue_size_outside_c_int_is_rejected_before_ffi(fake_lib, queue_size):
lib = fake_lib({"type": "ok"})
with pytest.raises(ValueError, match="does not fit C int"):
migrate_init(queue_size)
assert lib.calls == []
def test_queue_size_on_old_lib_raises_clear_error(monkeypatch):
lib = OldLib({"type": "ok"})
monkeypatch.setattr(core._native, "lib", lambda: lib)
with pytest.raises(RuntimeError, match="does not export chat_migrate_init_queue"):
migrate_init(65536)
assert lib.calls == []
def test_setup_signatures_accepts_old_lib():
class Fn:
argtypes: Any = None
restype: Any = None
class Lib:
def __getattr__(self, name: str) -> Fn:
if name == "chat_migrate_init_queue":
raise AttributeError(name)
fn = Fn()
setattr(self, name, fn)
return fn
from simplex_chat import _native
_native._setup_signatures(Lib()) # type: ignore[arg-type]
@@ -0,0 +1,121 @@
from __future__ import annotations
import asyncio
import base64
from typing import Any
import pytest
from simplex_chat import core
JPEG = b"\xff\xd8\xff\xe0"
class FakeLib:
def __init__(self, result: str) -> None:
self.result = result
self.calls: list[tuple[str, tuple[Any, ...]]] = []
def _export(self, name: str) -> Any:
lib = self
class Fn:
argtypes: Any = None
restype: Any = None
def __call__(self, *args: Any) -> str:
lib.calls.append((name, args))
return lib.result
return Fn()
@property
def chat_resize_image(self) -> Any:
return self._export("chat_resize_image")
@property
def chat_resize_image_uri(self) -> Any:
return self._export("chat_resize_image_uri")
@pytest.fixture
def fake_lib(monkeypatch: pytest.MonkeyPatch):
def install(result: str) -> FakeLib:
lib = FakeLib(result)
monkeypatch.setattr(core._native, "lib", lambda: lib)
monkeypatch.setattr(core, "_read_and_free", lambda ptr: ptr)
return lib
return install
def test_resize_image_uri_returns_the_data_uri(fake_lib):
lib = fake_lib("data:image/jpg;base64,AAAA")
assert asyncio.run(core.chat_resize_image_uri(b"image", 14000)) == "data:image/jpg;base64,AAAA"
assert lib.calls == [("chat_resize_image_uri", (b"image", 5, 14000))]
@pytest.mark.parametrize(("image_format", "png"), [("jpeg", 0), ("png", 1)])
def test_resize_image_passes_the_format_and_decodes_base64(fake_lib, image_format, png):
lib = fake_lib(base64.b64encode(JPEG).decode())
assert asyncio.run(core.chat_resize_image(b"image", 261120, image_format)) == JPEG
assert lib.calls == [("chat_resize_image", (b"image", 5, 261120, png))]
def test_resize_image_leaves_the_format_to_the_core(fake_lib):
lib = fake_lib(base64.b64encode(JPEG).decode())
assert asyncio.run(core.resize_image(b"image", core.ImageSize.IMAGE)) == JPEG
assert lib.calls == [("chat_resize_image", (b"image", 5, 261120, -1))]
@pytest.mark.parametrize(
("size", "max_size"),
[(core.ImageSize.PROFILE_PREVIEW, 12500), (core.ImageSize.MESSAGE_PREVIEW, 14000)],
)
def test_resize_image_previews_return_the_data_uri(fake_lib, size, max_size):
lib = fake_lib("data:image/png;base64,AAAA")
assert asyncio.run(core.resize_image(b"image", size)) == "data:image/png;base64,AAAA"
assert lib.calls == [("chat_resize_image_uri", (b"image", 5, max_size))]
@pytest.mark.parametrize(
"resize",
[
lambda: core.chat_resize_image_uri(b"image", 14000),
lambda: core.chat_resize_image(b"image", 261120, "jpeg"),
lambda: core.resize_image(b"image", core.ImageSize.IMAGE),
],
)
def test_empty_result_raises(fake_lib, resize):
fake_lib("")
with pytest.raises(RuntimeError, match="image cannot be decoded or does not fit max_size"):
asyncio.run(resize())
@pytest.mark.parametrize(
("name", "resize"),
[
("chat_resize_image_uri", lambda: core.chat_resize_image_uri(b"image", 14000)),
("chat_resize_image", lambda: core.chat_resize_image(b"image", 261120, "png")),
("chat_resize_image", lambda: core.resize_image(b"image", core.ImageSize.IMAGE)),
(
"chat_resize_image_uri",
lambda: core.resize_image(b"image", core.ImageSize.PROFILE_PREVIEW),
),
],
)
def test_old_lib_raises_clear_error(monkeypatch, name, resize):
monkeypatch.setattr(core._native, "lib", lambda: object())
message = f"loaded libsimplex does not export {name}; image resizing needs a newer libsimplex"
with pytest.raises(RuntimeError, match=message):
asyncio.run(resize())
@pytest.mark.parametrize("max_size", [2**31, -(2**31) - 1])
def test_max_size_outside_c_int_is_rejected_before_ffi(fake_lib, max_size):
lib = fake_lib("data:image/jpg;base64,AAAA")
with pytest.raises(ValueError, match="does not fit C int"):
asyncio.run(core.chat_resize_image_uri(b"image", max_size))
with pytest.raises(ValueError, match="does not fit C int"):
asyncio.run(core.chat_resize_image(b"image", max_size, "jpeg"))
assert lib.calls == []
@@ -1,10 +1,12 @@
import hashlib
import zipfile
from pathlib import Path
import pytest
from simplex_chat._native import _cache_root, _download, _resolve_libs_dir
from simplex_chat._version import LIBS_VERSION
from simplex_chat import _native
from simplex_chat._native import _cache_root, _download, _resolve_libs_dir, lib_for
from simplex_chat._version import LIBS_RELEASE
def test_cache_root_linux(tmp_path, monkeypatch):
@@ -42,7 +44,7 @@ def test_resolve_downloads_when_missing(tmp_path, monkeypatch):
monkeypatch.setattr("simplex_chat._native._download", fake_download)
libs_dir = _resolve_libs_dir("sqlite")
assert libs_dir == tmp_path / "simplex-chat" / f"v{LIBS_VERSION}" / "sqlite"
assert libs_dir == tmp_path / "simplex-chat" / LIBS_RELEASE / "sqlite"
assert called["backend"] == "sqlite"
assert (libs_dir / "libsimplex.so").exists()
@@ -50,7 +52,7 @@ def test_resolve_downloads_when_missing(tmp_path, monkeypatch):
def test_resolve_uses_cache_on_second_call(tmp_path, monkeypatch):
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path))
monkeypatch.setattr("sys.platform", "linux")
cached = tmp_path / "simplex-chat" / f"v{LIBS_VERSION}" / "sqlite"
cached = tmp_path / "simplex-chat" / LIBS_RELEASE / "sqlite"
cached.mkdir(parents=True)
(cached / "libsimplex.so").touch()
# Should NOT call _download — use the cached file.
@@ -67,9 +69,8 @@ def test_postgres_on_macos_rejected(monkeypatch):
_resolve_libs_dir("postgres")
def test_atomic_install(tmp_path, monkeypatch):
"""Build a fake libs zip, mock _stream_to_file, verify extraction + atomic rename."""
# Build zip: libs/libsimplex.so + libs/libHS-stub.so
def fake_libs_zip(tmp_path, monkeypatch, sha256=None) -> None:
"""Serve a zip with libs/libsimplex.so + libs/libHS-stub.so, pinned with `sha256` (its own by default)."""
src = tmp_path / "src" / "libs"
src.mkdir(parents=True)
(src / "libsimplex.so").write_text("fake-so")
@@ -84,10 +85,54 @@ def test_atomic_install(tmp_path, monkeypatch):
shutil.copy(zip_path, dest)
pinned = sha256 or hashlib.sha256(zip_path.read_bytes()).hexdigest()
monkeypatch.setattr("simplex_chat._native._stream_to_file", fake_stream)
monkeypatch.setattr("simplex_chat._native._platform_tag", lambda: "linux-x86_64")
monkeypatch.setattr(
"simplex_chat._native.LIBS_SHA256", {"simplex-chat-libs-linux-x86_64.zip": pinned}
)
def test_atomic_install(tmp_path, monkeypatch):
fake_libs_zip(tmp_path, monkeypatch)
target = tmp_path / "out"
_download(target, "sqlite")
assert (target / "libsimplex.so").read_text() == "fake-so"
assert (target / "libHS-stub.so").read_text() == "fake-hs"
def test_download_rejects_another_sha256(tmp_path, monkeypatch):
fake_libs_zip(tmp_path, monkeypatch, sha256="0" * 64)
target = tmp_path / "out"
with pytest.raises(RuntimeError, match=f"expected {'0' * 64}"):
_download(target, "sqlite")
assert sorted(p.name for p in tmp_path.iterdir()) == ["fake-libs.zip", "src"]
def test_download_requires_pinned_sha256(tmp_path, monkeypatch):
fake_libs_zip(tmp_path, monkeypatch)
with pytest.raises(
RuntimeError, match="no SHA-256 is pinned for simplex-chat-libs-linux-x86_64-postgres.zip"
):
_download(tmp_path / "out", "postgres")
def test_libc_on_windows_is_ucrt(monkeypatch):
loaded: list[str | None] = []
monkeypatch.setattr("sys.platform", "win32")
monkeypatch.setattr("ctypes.CDLL", lambda name: loaded.append(name))
_native._load_libc()
assert loaded == ["ucrtbase"]
def test_lib_for_rejects_backend_switch(monkeypatch):
monkeypatch.setattr(_native, "_lib", object())
monkeypatch.setattr(_native, "_backend", "sqlite")
monkeypatch.setattr(
_native, "_resolve_libs_dir", lambda _: pytest.fail("must not resolve libs")
)
with pytest.raises(RuntimeError) as exc:
lib_for("postgres")
assert str(exc.value) == (
"libsimplex already loaded with backend=sqlite; cannot switch to postgres in the same process"
)
@@ -3,7 +3,7 @@ from unittest.mock import patch
import pytest
from simplex_chat._native import _libname, _libs_url, _platform_tag
from simplex_chat._version import LIBS_VERSION
from simplex_chat._version import LIBS_RELEASE
@patch("sys.platform", "linux")
@@ -45,7 +45,7 @@ def test_url_sqlite(_):
assert (
_libs_url("sqlite")
== "https://github.com/simplex-chat/simplex-chat-libs/releases/download/"
f"v{LIBS_VERSION}/simplex-chat-libs-linux-x86_64.zip"
f"{LIBS_RELEASE}/simplex-chat-libs-linux-x86_64.zip"
)
@@ -54,5 +54,5 @@ def test_url_postgres(_):
assert (
_libs_url("postgres")
== "https://github.com/simplex-chat/simplex-chat-libs/releases/download/"
f"v{LIBS_VERSION}/simplex-chat-libs-linux-x86_64-postgres.zip"
f"{LIBS_RELEASE}/simplex-chat-libs-linux-x86_64-postgres.zip"
)
@@ -0,0 +1,207 @@
"""ChatApi receives run on a dedicated per-instance thread, not the default pool.
Uses a fake libsimplex (see tests/test_core_migrate_init.py for the pattern):
`core._native.lib` and `core._read_and_free` are monkeypatched so `chat_recv_msg_wait`
sleeps for a controlled time and returns a scripted result.
"""
from __future__ import annotations
import asyncio
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import pytest
from simplex_chat import ChatApi, ChatCommandError
RECV_SLEEP = 0.3
class FakeRecvLib:
"""Fake chat_recv_msg_wait: blocks for `sleep` seconds, then returns a scripted result.
`events` records "stop" / "recv_start" / "recv_end" / "close_store" in call order, across
all ChatApi instances sharing this fake, so tests can assert ordering between stop, receive
and store-close calls (not just that they happened).
"""
def __init__(
self,
sleep: float = RECV_SLEEP,
results: list[str] | None = None,
stop_response: str = "chatStopped",
) -> None:
self.sleep = sleep
self._results = iter(results or [])
self._stop_response = stop_response
self.calls: list[tuple[int, int]] = [] # (ctrl, thread ident)
self.events: list[str] = []
self._lock = threading.Lock()
def chat_recv_msg_wait(self, ctrl: int, wait_us: int) -> str:
with self._lock:
self.events.append("recv_start")
time.sleep(self.sleep)
with self._lock:
self.events.append("recv_end")
self.calls.append((ctrl, threading.get_ident()))
return next(self._results, "")
def chat_send_cmd(self, ctrl: int, cmd: bytes) -> str:
assert cmd == b"/_stop", f"unexpected command {cmd!r}"
with self._lock:
self.events.append("stop")
return json.dumps({"result": {"type": self._stop_response}})
def chat_close_store(self, ctrl: int) -> str:
with self._lock:
self.events.append("close_store")
return ""
@pytest.fixture
def fake_lib(monkeypatch: pytest.MonkeyPatch):
def install(
sleep: float = RECV_SLEEP,
results: list[str] | None = None,
stop_response: str = "chatStopped",
) -> FakeRecvLib:
lib = FakeRecvLib(sleep=sleep, results=results, stop_response=stop_response)
monkeypatch.setattr("simplex_chat.core._native.lib", lambda: lib)
monkeypatch.setattr("simplex_chat.core._read_and_free", lambda ptr: ptr)
return lib
return install
def _recv_thread_names() -> list[str]:
return [t.name for t in threading.enumerate() if t.name.startswith("simplex-recv")]
async def test_receives_do_not_use_the_default_executor(fake_lib):
fake_lib(sleep=RECV_SLEEP)
loop = asyncio.get_running_loop()
loop.set_default_executor(ThreadPoolExecutor(max_workers=1))
apis = [ChatApi(ctrl=i) for i in range(3)]
recv_tasks = [asyncio.create_task(api.recv_chat_event()) for api in apis]
try:
await asyncio.sleep(0.05) # let all three receives claim their own thread
start = time.monotonic()
await asyncio.to_thread(lambda: None)
elapsed = time.monotonic() - start
await asyncio.gather(*recv_tasks)
finally:
for api in apis:
await api.close()
assert elapsed < 0.1
async def test_one_receive_thread_per_chatapi_reused(fake_lib):
lib = fake_lib(sleep=0.02)
api = ChatApi(ctrl=1)
other_api = ChatApi(ctrl=2)
try:
for _ in range(3):
await api.recv_chat_event()
idents = {ident for ctrl, ident in lib.calls if ctrl == 1}
assert len(idents) == 1
recv_ident = idents.pop()
thread = next(t for t in threading.enumerate() if t.ident == recv_ident)
assert thread.name.startswith("simplex-recv")
assert thread.ident != threading.get_ident()
await other_api.recv_chat_event()
other_idents = {ident for ctrl, ident in lib.calls if ctrl == 2}
assert other_idents and other_idents != {thread.ident}
finally:
await api.close()
await other_api.close()
def test_no_thread_until_first_receive():
# A bare ThreadPoolExecutor spawns no worker thread until the first submit,
# so the real assertion is the attribute itself, not threading.enumerate().
api = ChatApi(ctrl=1)
assert api._recv_executor is None
async def test_close_shuts_down_the_executor_without_blocking_the_loop(fake_lib):
fake_lib(sleep=RECV_SLEEP)
api = ChatApi(ctrl=1)
recv_task = asyncio.create_task(api.recv_chat_event())
await asyncio.sleep(0.05) # let the receive claim its executor thread
assert _recv_thread_names() != []
sleep_task = asyncio.create_task(asyncio.sleep(0.01))
close_task = asyncio.create_task(api.close())
await asyncio.wait_for(sleep_task, timeout=0.2)
assert not close_task.done() # shutdown still waiting on the in-flight receive
await close_task
await recv_task
assert _recv_thread_names() == []
async def test_close_shuts_down_executor_before_closing_the_store(fake_lib):
lib = fake_lib(sleep=RECV_SLEEP)
api = ChatApi(ctrl=1)
recv_task = asyncio.create_task(api.recv_chat_event())
try:
await asyncio.sleep(0.05) # ensure the receive is in flight before close() starts
await api.close()
await recv_task
finally:
if not recv_task.done():
recv_task.cancel()
# recv_end (executor drained) must precede close_store: a receive must never
# be in flight while the store closes underneath it.
assert lib.events == ["recv_start", "stop", "recv_end", "close_store"]
async def test_close_stops_the_chat_before_closing_the_store(fake_lib):
lib = fake_lib()
api = ChatApi(ctrl=1)
await api.close()
assert lib.events == ["stop", "close_store"]
assert not api.initialized
async def test_close_does_not_close_the_store_when_stop_fails(fake_lib):
lib = fake_lib(stop_response="chatCmdError")
api = ChatApi(ctrl=1)
with pytest.raises(ChatCommandError, match="error stopping chat"):
await api.close()
assert lib.events == ["stop"]
assert api.initialized
async def test_recv_chat_event_after_close_raises_before_touching_executor(fake_lib):
fake_lib()
api = ChatApi(ctrl=1)
await api.close()
with pytest.raises(RuntimeError, match="controller not initialized"):
await api.recv_chat_event()
assert api._recv_executor is None
async def test_receive_parses_event_json_and_none_on_timeout(fake_lib):
event: dict[str, Any] = {"type": "chatItemUpdated", "chatItem": {}}
fake_lib(sleep=0.01, results=[json.dumps({"result": event}), ""])
api = ChatApi(ctrl=1)
try:
assert await api.recv_chat_event() == event
assert await api.recv_chat_event() is None
finally:
await api.close()
@@ -167,6 +167,11 @@ def test_ci_bot_command_no_text():
assert util.ci_bot_command(ci) is None
def test_ci_bot_command_multiline_params():
ci = {"content": {"type": "rcvMsgContent", "msgContent": {"type": "text", "text": "/review line1\nline2"}}}
assert util.ci_bot_command(ci) == ("review", "line1\nline2")
def test_reaction_text_emoji():
r = {"chatReaction": {"reaction": {"type": "emoji", "emoji": "🎉"}}}
assert util.reaction_text(r) == "🎉"