Skip to main content

byob_protocol/
phone.rs

1//! "My phone" on the wire (13.23+, cap [`CAP_PHONE`]): the channel byob texts you on and the
2//! person paired on it (see [`byob_types::channel`]).
3//!
4//! The engine sends [`crate::ServerMsg::Phone`] after the Welcome and whenever it changes:
5//! the channels plugins offer, whether My phone is set up, a pairing in progress. Setting a
6//! channel's own settings (a bot token) and switching its plugin on are the ordinary plugin
7//! messages (`SetPluginSetting`, `SetPluginEnabled`). Peer ids never reach clients: only the
8//! name the channel gave the person.
9
10use serde::{Deserialize, Serialize};
11
12pub use byob_types::channel::{CHANNEL_PHONE, DAILY_CAP};
13
14use crate::ClientMsg;
15
16/// Cap: the peer handles the phone messages.
17pub const CAP_PHONE: &str = "phone";
18
19/// A channel a plugin offers.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
21pub struct ChannelOption {
22    /// `<plugin>:<channel>`.
23    pub key: String,
24    pub plugin: String,
25    /// "Telegram".
26    pub title: String,
27    /// The user can answer (replies, buttons).
28    #[serde(default)]
29    pub two_way: bool,
30    /// Approvals can be answered with a tap.
31    #[serde(default)]
32    pub buttons: bool,
33    /// Its plugin is switched on.
34    #[serde(default)]
35    pub enabled: bool,
36    /// Its plugin's required settings are filled in.
37    #[serde(default)]
38    pub configured: bool,
39    /// Its backend says it works (`channel_status` ok), as of `status`.
40    #[serde(default)]
41    pub ok: bool,
42    /// What its backend last said about itself ("Connected as @byob_jesse_bot", "Telegram
43    /// refused the bot token"), or why it isn't running.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub status: Option<String>,
46    /// The setting the user fills in to set it up (Telegram: `BOT_TOKEN`), if any.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub setting: Option<String>,
49    /// That setting's label ("Bot token").
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub setting_label: Option<String>,
52    /// That setting's help (the setup steps).
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub setting_help: Option<String>,
55}
56
57/// My phone, set up.
58#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
59pub struct PhoneView {
60    pub channel: String,
61    /// The channel's title.
62    pub title: String,
63    /// What the channel called the person ("@jesse").
64    #[serde(default)]
65    pub name: String,
66    /// ms since the epoch.
67    #[serde(default)]
68    pub paired_at: i64,
69}
70
71/// A pairing in progress.
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Pairing {
74    pub channel: String,
75    /// The code, as people read it (`ABCD-EFGH`).
76    pub code: String,
77    /// A link that pairs with one tap (`https://t.me/<bot>?start=<code>`).
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub link: Option<String>,
80    /// Who to send the code to ("@byob_jesse_bot").
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub name: Option<String>,
83    /// The channel's own steps.
84    #[serde(default)]
85    pub instructions: String,
86    /// When the code stops working (ms).
87    pub expires_at: i64,
88}
89
90/// Everything a client shows about My phone.
91#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
92pub struct PhoneState {
93    #[serde(default)]
94    pub channels: Vec<ChannelOption>,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub phone: Option<PhoneView>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub pairing: Option<Pairing>,
99}
100
101/// Size checks of the phone messages.
102pub(crate) fn check_sizes(msg: &ClientMsg) -> Result<(), String> {
103    match msg {
104        ClientMsg::PairPhone { channel } if channel.len() > 200 || byob_types::channel::split_key(channel).is_none() => Err("bad channel".into()),
105        _ => Ok(()),
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::ServerMsg;
113
114    #[test]
115    fn phone_messages_round_trip() {
116        for m in [ClientMsg::PairPhone { channel: "telegram:telegram".into() }, ClientMsg::CancelPairing, ClientMsg::UnpairPhone, ClientMsg::TestPhone] {
117            assert!(m.check_sizes().is_ok());
118            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
119        }
120        assert!(ClientMsg::PairPhone { channel: "nope".into() }.check_sizes().is_err());
121        let s = ServerMsg::Phone(PhoneState {
122            channels: vec![ChannelOption {
123                key: "telegram:telegram".into(),
124                plugin: "telegram".into(),
125                title: "Telegram".into(),
126                two_way: true,
127                ..Default::default()
128            }],
129            phone: Some(PhoneView { channel: "telegram:telegram".into(), title: "Telegram".into(), name: "@jesse".into(), paired_at: 5 }),
130            pairing: Some(Pairing { channel: "telegram:telegram".into(), code: "ABCD-EFGH".into(), expires_at: 9, ..Default::default() }),
131        });
132        let json = serde_json::to_string(&s).unwrap();
133        assert_eq!(ServerMsg::from_json(&json).unwrap(), s, "{json}");
134    }
135}