Skip to main content

zaun_community_protocol/command/
bot.rs

1//! Bot management commands (specification §8.13). Install, update, grant, enable, disable,
2//! remove and register are the owner's alone; list and get are open to every member.
3
4use serde::{Deserialize, Serialize};
5
6use std::collections::BTreeMap;
7
8use super::object::{BotCard, Capabilities, Grants, config_key_ok};
9use super::{BodyError, Validate, check};
10use crate::bits::Permissions;
11use crate::ids::{AttachmentId, BotId, MemberId};
12use crate::limits::{BOT_CONFIG_KEYS, BOT_CONFIG_VALUE_MAX, DISPLAY_NAME};
13
14/// Optional grant choices of `bot.install`: absent means everything the manifest asks for,
15/// within the operator's ceiling.
16#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
17pub struct GrantChoice {
18    /// Permission bits.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub permissions: Option<Permissions>,
21    /// Capabilities.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub capabilities: Option<Capabilities>,
24}
25
26impl Validate for GrantChoice {
27    fn validate(&self) -> Result<(), BodyError> {
28        if let Some(bits) = self.permissions {
29            check::known_bits("grants.permissions", bits)?;
30        }
31        self.capabilities
32            .as_ref()
33            .map_or(Ok(()), |c| c.check("grants.capabilities"))
34    }
35}
36
37/// `bot.install`.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Install {
40    /// A stored attachment the owner uploaded, holding the `.zbot` package.
41    pub package: AttachmentId,
42    /// What to grant.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub grants: Option<GrantChoice>,
45    /// Where the managed role goes (default: directly above `@everyone`).
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub role_position: Option<u32>,
48}
49
50/// `bot.update`.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52pub struct Update {
53    /// The bot.
54    pub bot_id: BotId,
55    /// The new package.
56    pub package: AttachmentId,
57}
58
59/// `bot.grant`: the new effective grants, replacing the old.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Grant {
62    /// The bot.
63    pub bot_id: BotId,
64    /// Bits of the managed role.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub permissions: Option<Permissions>,
67    /// Capabilities.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub capabilities: Option<Capabilities>,
70}
71
72/// `bot.enable`, `bot.disable`, `bot.get`.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74pub struct Target {
75    /// The bot.
76    pub bot_id: BotId,
77}
78
79/// `bot.remove`.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81pub struct Remove {
82    /// The bot.
83    pub bot_id: BotId,
84    /// Delete its storage and package too (default true).
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub delete_data: Option<bool>,
87}
88
89/// `bot.register`: mark an existing member as an external bot.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Register {
92    /// The member.
93    pub member_id: MemberId,
94    /// The card's name (default: the member's display name).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub name: Option<String>,
97}
98
99/// `bot.configure`: the owner sets or clears values of the settings the bot's manifest
100/// declares. With neither, it only reads them.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct Configure {
103    /// The bot.
104    pub bot_id: BotId,
105    /// Values to set, by key.
106    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
107    pub set: BTreeMap<String, String>,
108    /// Keys to clear (back to their default).
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub unset: Vec<String>,
111}
112
113/// `bot.configure` response: the values the owner set, secrets shown as `"••••"`.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Configured {
116    /// Key to value.
117    pub values: BTreeMap<String, String>,
118}
119
120/// How a secret value is shown.
121pub const MASKED: &str = "••••";
122
123impl Validate for Configure {
124    fn validate(&self) -> Result<(), BodyError> {
125        check::count("set", self.set.len(), BOT_CONFIG_KEYS)?;
126        check::count("unset", self.unset.len(), BOT_CONFIG_KEYS)?;
127        for (key, value) in &self.set {
128            if !config_key_ok(key) {
129                return Err(BodyError::bad(&format!("config.{key}"), "is not a key"));
130            }
131            if value.len() > BOT_CONFIG_VALUE_MAX {
132                return Err(BodyError::bad(&format!("config.{key}"), "is over 4 KiB"));
133            }
134        }
135        if let Some(key) = self.unset.iter().find(|k| !config_key_ok(k)) {
136            return Err(BodyError::bad(&format!("config.{key}"), "is not a key"));
137        }
138        Ok(())
139    }
140}
141
142/// `bot.list`.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
144pub struct List {}
145
146/// `bot.list` response.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Bots {
149    /// Every installed bot.
150    pub bots: Vec<BotCard>,
151}
152
153/// `bot.enable` (distinct type so the command table can name it).
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155pub struct Enable {
156    /// The bot.
157    pub bot_id: BotId,
158}
159
160/// `bot.disable`.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
162pub struct Disable {
163    /// The bot.
164    pub bot_id: BotId,
165}
166
167impl Validate for Install {
168    fn validate(&self) -> Result<(), BodyError> {
169        self.grants.as_ref().map_or(Ok(()), Validate::validate)
170    }
171}
172
173impl Validate for Grant {
174    fn validate(&self) -> Result<(), BodyError> {
175        if self.permissions.is_none() && self.capabilities.is_none() {
176            return Err(BodyError::bad(
177                "permissions",
178                "give permissions or capabilities",
179            ));
180        }
181        GrantChoice {
182            permissions: self.permissions,
183            capabilities: self.capabilities.clone(),
184        }
185        .validate()
186    }
187}
188
189impl Validate for Register {
190    fn validate(&self) -> Result<(), BodyError> {
191        check::opt_text("name", self.name.as_deref(), DISPLAY_NAME)
192    }
193}
194
195macro_rules! no_checks {
196    ($($t:ty),*) => { $(impl Validate for $t { fn validate(&self) -> Result<(), BodyError> { Ok(()) } })* };
197}
198no_checks!(Update, Target, Remove, List, Enable, Disable);
199
200/// Full grants from a choice and the manifest's request.
201#[must_use]
202pub fn chosen(choice: Option<&GrantChoice>, request: &Grants) -> Grants {
203    Grants {
204        permissions: choice
205            .and_then(|c| c.permissions)
206            .unwrap_or(request.permissions),
207        capabilities: choice
208            .and_then(|c| c.capabilities.clone())
209            .unwrap_or_else(|| request.capabilities.clone()),
210    }
211}