Skip to main content

zaun_client/dm/
wire.rs

1//! A DM channel as the client keeps it, built from the protocol's channel object of kind
2//! `dm` (specification ยง8.13); the member's DM setting is the protocol's.
3
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6use zaun_community_protocol::command::object::Channel;
7use zaun_community_protocol::ids::{ChannelId, MemberId};
8use zaun_community_protocol::model::ChannelKind;
9
10pub use zaun_community_protocol::command::dm::Settings as DmSettings;
11
12/// A DM channel: an ordinary channel object of kind `dm` with its two participants.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct DmChannel {
15    /// The channel.
16    pub channel_id: ChannelId,
17    /// Its two members, sorted.
18    pub participants: [MemberId; 2],
19    /// The rest of the channel object, as the host sent it.
20    #[serde(flatten)]
21    pub rest: Map<String, Value>,
22}
23
24impl DmChannel {
25    /// A DM learnt only from a message in it: the two members, no other field.
26    #[must_use]
27    pub fn between(channel_id: ChannelId, a: MemberId, b: MemberId) -> Self {
28        let participants = if a <= b { [a, b] } else { [b, a] };
29        Self {
30            channel_id,
31            participants,
32            rest: Map::new(),
33        }
34    }
35
36    /// The DM a channel object describes; `None` for any other kind of channel, or a DM
37    /// without exactly two participants.
38    #[must_use]
39    pub fn from_channel(channel: &Channel) -> Option<Self> {
40        if channel.kind != ChannelKind::Dm {
41            return None;
42        }
43        let Value::Object(map) = serde_json::to_value(channel).ok()? else {
44            return None;
45        };
46        serde_json::from_value(Value::Object(map)).ok()
47    }
48
49    /// The participant who is not `me` (`me` when both are).
50    #[must_use]
51    pub fn other(&self, me: MemberId) -> MemberId {
52        let [a, b] = self.participants;
53        if a == me { b } else { a }
54    }
55}
56
57/// `dm.list`'s answer, read as client DM channels.
58#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
59pub(crate) struct DmChannels {
60    pub(crate) channels: Vec<DmChannel>,
61}