Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

api!(deltachat-jsonrpc): use kind as a tag for all union types #4602

Merged
merged 1 commit into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion deltachat-jsonrpc/src/api/types/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use typescript_type_def::TypeDef;
use super::color_int_to_hex_string;

#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "type")]
#[serde(tag = "kind")]
pub enum Account {
#[serde(rename_all = "camelCase")]
Configured {
Expand Down
9 changes: 5 additions & 4 deletions deltachat-jsonrpc/src/api/types/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,24 +167,25 @@ impl BasicChat {
}

#[derive(Clone, Serialize, Deserialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum MuteDuration {
NotMuted,
Forever,
Until(i64),
Until { duration: i64 },
}

impl MuteDuration {
pub fn try_into_core_type(self) -> Result<chat::MuteDuration> {
match self {
MuteDuration::NotMuted => Ok(chat::MuteDuration::NotMuted),
MuteDuration::Forever => Ok(chat::MuteDuration::Forever),
MuteDuration::Until(n) => {
if n <= 0 {
MuteDuration::Until { duration } => {
if duration <= 0 {
bail!("failed to read mute duration")
}

Ok(SystemTime::now()
.checked_add(Duration::from_secs(n as u64))
.checked_add(Duration::from_secs(duration as u64))
.map_or(chat::MuteDuration::Forever, chat::MuteDuration::Until))
}
}
Expand Down
2 changes: 1 addition & 1 deletion deltachat-jsonrpc/src/api/types/chat_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::message::MessageViewtype;
pub struct ChatListEntry(pub u32, pub u32);

#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "type")]
#[serde(tag = "kind")]
pub enum ChatListItemFetchResult {
#[serde(rename_all = "camelCase")]
ChatListItem {
Expand Down
2 changes: 1 addition & 1 deletion deltachat-jsonrpc/src/api/types/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl From<CoreEvent> for Event {
}

#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(tag = "type")]
#[serde(tag = "kind")]
pub enum EventType {
/// The library-user may write an informational string to the log.
///
Expand Down
2 changes: 1 addition & 1 deletion deltachat-jsonrpc/src/api/types/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use super::reactions::JSONRPCReactions;
use super::webxdc::WebxdcMessageInfo;

#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", tag = "variant")]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum MessageLoadResult {
Message(MessageObject),
LoadingError { error: String },
Expand Down
2 changes: 1 addition & 1 deletion deltachat-jsonrpc/src/api/types/qr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use typescript_type_def::TypeDef;

#[derive(Serialize, TypeDef, schemars::JsonSchema)]
#[serde(rename = "Qr", rename_all = "camelCase")]
#[serde(tag = "type")]
#[serde(tag = "kind")]
pub enum QrObject {
AskVerifyContact {
contact_id: u32,
Expand Down
11 changes: 5 additions & 6 deletions deltachat-jsonrpc/typescript/example/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async function run() {
const accounts = await client.rpc.getAllAccounts();
console.log("accounts loaded", accounts);
for (const account of accounts) {
if (account.type === "Configured") {
if (account.kind === "Configured") {
write(
$head,
`<a href="#" onclick="selectDeltaAccount(${account.id})">
Expand All @@ -57,7 +57,7 @@ async function run() {
clear($main);
const selectedAccount = SELECTED_ACCOUNT;
const info = await client.rpc.getAccountInfo(selectedAccount);
if (info.type !== "Configured") {
if (info.kind !== "Configured") {
return write($main, "Account is not configured");
}
write($main, `<h2>${info.addr!}</h2>`);
Expand All @@ -81,8 +81,7 @@ async function run() {
messageIds
);
for (const [_messageId, message] of Object.entries(messages)) {
if (message.variant === "message")
write($main, `<p>${message.text}</p>`);
if (message.kind === "message") write($main, `<p>${message.text}</p>`);
else write($main, `<p>loading error: ${message.error}</p>`);
}
}
Expand All @@ -93,9 +92,9 @@ async function run() {
$side,
`
<p class="message">
[<strong>${event.type}</strong> on account ${accountId}]<br>
[<strong>${event.kind}</strong> on account ${accountId}]<br>
<em>f1:</em> ${JSON.stringify(
Object.assign({}, event, { type: undefined })
Object.assign({}, event, { kind: undefined })
)}
</p>`
);
Expand Down
16 changes: 8 additions & 8 deletions deltachat-jsonrpc/typescript/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ import { WebsocketTransport, BaseTransport, Request } from "yerpc";
import { TinyEmitter } from "@deltachat/tiny-emitter";

type Events = { ALL: (accountId: number, event: EventType) => void } & {
[Property in EventType["type"]]: (
[Property in EventType["kind"]]: (
accountId: number,
event: Extract<EventType, { type: Property }>
event: Extract<EventType, { kind: Property }>
) => void;
};

type ContextEvents = { ALL: (event: EventType) => void } & {
[Property in EventType["type"]]: (
event: Extract<EventType, { type: Property }>
[Property in EventType["kind"]]: (
event: Extract<EventType, { kind: Property }>
) => void;
};

export type DcEvent = EventType;
export type DcEventType<T extends EventType["type"]> = Extract<
export type DcEventType<T extends EventType["kind"]> = Extract<
EventType,
{ type: T }
{ kind: T }
>;

export class BaseDeltaChat<
Expand All @@ -46,12 +46,12 @@ export class BaseDeltaChat<
while (true) {
const event = await this.rpc.getNextEvent();
//@ts-ignore
this.emit(event.event.type, event.contextId, event.event);
this.emit(event.event.kind, event.contextId, event.event);
this.emit("ALL", event.contextId, event.event);

if (this.contextEmitters[event.contextId]) {
this.contextEmitters[event.contextId].emit(
event.event.type,
event.event.kind,
//@ts-ignore
event.event as any
);
Expand Down
8 changes: 4 additions & 4 deletions deltachat-jsonrpc/typescript/test/online.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ describe("online tests", function () {
serverHandle = await startServer();
dc = new DeltaChat(serverHandle.stdin, serverHandle.stdout, true);

dc.on("ALL", (contextId, { type }) => {
if (type !== "Info") console.log(contextId, type);
dc.on("ALL", (contextId, { kind }) => {
if (kind !== "Info") console.log(contextId, kind);
});

account1 = await createTempUser(process.env.DCC_NEW_TMP_EMAIL);
Expand Down Expand Up @@ -177,12 +177,12 @@ describe("online tests", function () {
});
});

async function waitForEvent<T extends DcEvent["type"]>(
async function waitForEvent<T extends DcEvent["kind"]>(
dc: DeltaChat,
eventType: T,
accountId: number,
timeout: number = EVENT_TIMEOUT
): Promise<Extract<DcEvent, { type: T }>> {
): Promise<Extract<DcEvent, { kind: T }>> {
return new Promise((resolve, reject) => {
const rejectTimeout = setTimeout(
() => reject(new Error("Timeout reached before event came in")),
Expand Down
4 changes: 2 additions & 2 deletions deltachat-rpc-client/examples/echobot_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

@hooks.on(events.RawEvent)
async def log_event(event):
if event.type == EventType.INFO:
if event.kind == EventType.INFO:
logging.info(event.msg)
elif event.type == EventType.WARNING:
elif event.kind == EventType.WARNING:
logging.warning(event.msg)


Expand Down
6 changes: 3 additions & 3 deletions deltachat-rpc-client/src/deltachat_rpc_client/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ async def mute(self, duration: Optional[int] = None) -> None:
"""
if duration is not None:
assert duration > 0, "Invalid duration"
dur: Union[str, dict] = {"Until": duration}
dur: dict = {"kind": "Until", "duration": duration}
else:
dur = "Forever"
dur = {"kind": "Forever"}
await self._rpc.set_chat_mute_duration(self.account.id, self.id, dur)

async def unmute(self) -> None:
"""Unmute this chat."""
await self._rpc.set_chat_mute_duration(self.account.id, self.id, "NotMuted")
await self._rpc.set_chat_mute_duration(self.account.id, self.id, {"kind": "NotMuted"})

async def pin(self) -> None:
"""Pin this chat."""
Expand Down
4 changes: 2 additions & 2 deletions deltachat-rpc-client/src/deltachat_rpc_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ async def run_until(self, func: Callable[[AttrDict], Union[bool, Coroutine]]) ->
await self._process_messages() # Process old messages.
while True:
event = await self.account.wait_for_event()
event["type"] = EventType(event.type)
event["kind"] = EventType(event.kind)
event["account"] = self.account
await self._on_event(event)
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
await self._process_messages()

stop = func(event)
Expand Down
2 changes: 1 addition & 1 deletion deltachat-rpc-client/src/deltachat_rpc_client/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __eq__(self, other) -> bool:
return False

async def filter(self, event: "AttrDict") -> bool:
if self.types and event.type not in self.types:
if self.types and event.kind not in self.types:
return False
return await self._call_func(event)

Expand Down
4 changes: 2 additions & 2 deletions deltachat-rpc-client/src/deltachat_rpc_client/pytestplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async def get_online_account(self) -> Account:
while True:
event = await account.wait_for_event()
print(event)
if event.type == EventType.IMAP_INBOX_IDLE:
if event.kind == EventType.IMAP_INBOX_IDLE:
break
return account

Expand Down Expand Up @@ -98,7 +98,7 @@ async def process_message(
group=group,
)

return await to_client.run_until(lambda e: e.type == EventType.INCOMING_MSG)
return await to_client.run_until(lambda e: e.kind == EventType.INCOMING_MSG)


@pytest_asyncio.fixture
Expand Down
10 changes: 5 additions & 5 deletions deltachat-rpc-client/tests/test_something.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async def test_acfactory(acfactory) -> None:
account = await acfactory.new_configured_account()
while True:
event = await account.wait_for_event()
if event.type == EventType.CONFIGURE_PROGRESS:
if event.kind == EventType.CONFIGURE_PROGRESS:
assert event.progress != 0 # Progress 0 indicates error.
if event.progress == 1000: # Success
break
Expand Down Expand Up @@ -76,7 +76,7 @@ async def test_account(acfactory) -> None:

while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
Expand Down Expand Up @@ -146,7 +146,7 @@ async def test_chat(acfactory) -> None:

while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
Expand Down Expand Up @@ -232,7 +232,7 @@ async def test_message(acfactory) -> None:

while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
chat_id = event.chat_id
msg_id = event.msg_id
break
Expand Down Expand Up @@ -272,7 +272,7 @@ async def test_is_bot(acfactory) -> None:

while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
msg_id = event.msg_id
message = bob.get_message_by_id(msg_id)
snapshot = await message.get_snapshot()
Expand Down
2 changes: 1 addition & 1 deletion deltachat-rpc-client/tests/test_webxdc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ async def test_webxdc(acfactory) -> None:

while True:
event = await bob.wait_for_event()
if event.type == EventType.INCOMING_MSG:
if event.kind == EventType.INCOMING_MSG:
bob_chat_alice = bob.get_chat_by_id(event.chat_id)
message = bob.get_message_by_id(event.msg_id)
break
Expand Down