Skip to main content

zaun_community_protocol/command/
channel.rs

1//! Channel commands (specification §8.2, permissions §2, §4.4). Responses are
2//! [`Channel`](super::object::Channel) or `{}`.
3//!
4//! SPEC: §8.2 lists `channel_id` in the bodies of `channel.update`, `channel.delete` and
5//! `channel.permissions.update`, while §7.1 puts it on the envelope for channel-scoped
6//! commands. It is optional here; [`Command::channel_id`](super::Command::channel_id) gives
7//! the body's value and the envelope layer requires one of the two (and equality if both).
8
9use serde::{Deserialize, Serialize};
10
11mod validate;
12
13use super::object::{ChannelPosition, Override, OverrideTarget, Retention};
14use super::{BodyError, Validate, check};
15use crate::ids::ChannelId;
16use crate::json::Patch;
17use crate::limits::{
18    CHANNEL_NAME, CHANNEL_TOPIC_MAX, OVERRIDES_PER_CHANNEL, SLOWMODE_MAX_S, VOICE_USER_LIMIT,
19};
20use crate::model::{ChannelKind, HistoryAccess, TypingMode};
21
22/// `channel.create` (§8.2).
23///
24/// SPEC: `history` and `sync_with_parent` are not create fields; they take their defaults
25/// and change through `channel.update`.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Create {
28    /// v1: `category`, `text`, `announcement`, `voice`; others are `UNSUPPORTED_FEATURE`.
29    pub kind: ChannelKind,
30    /// 1–100 scalars.
31    pub name: String,
32    /// ≤ 1 024 scalars.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub topic: Option<String>,
35    /// A category; categories have none.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub parent_id: Option<ChannelId>,
38    /// Position among siblings.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub position: Option<u32>,
41    /// 0–21 600 s.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub slowmode_s: Option<u32>,
44    /// Initial overrides, checked like `channel.permissions.update`.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub overrides: Option<Vec<Override>>,
47    /// Retention.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub retention: Option<Retention>,
50    /// Who sees typing (§10.5); absent: `named`.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub typing: Option<TypingMode>,
53    /// Voice channels only: the most participants, 1–99 (also capped by the host's
54    /// `mesh_max`); absent = the host's cap.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub user_limit: Option<u32>,
57}
58
59/// `channel.update` (§8.2): any of the fields; `null` clears only `topic` and `parent_id`.
60#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
61pub struct Update {
62    /// The channel (or on the envelope).
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub channel_id: Option<ChannelId>,
65    /// New name.
66    #[serde(default, skip_serializing_if = "Patch::is_keep")]
67    pub name: Patch<String>,
68    /// New topic; `null` clears.
69    #[serde(default, skip_serializing_if = "Patch::is_keep")]
70    pub topic: Patch<String>,
71    /// New parent; `null` moves to the top level.
72    #[serde(default, skip_serializing_if = "Patch::is_keep")]
73    pub parent_id: Patch<ChannelId>,
74    /// New slowmode.
75    #[serde(default, skip_serializing_if = "Patch::is_keep")]
76    pub slowmode_s: Patch<u32>,
77    /// Lock or unlock.
78    #[serde(default, skip_serializing_if = "Patch::is_keep")]
79    pub locked: Patch<bool>,
80    /// Who sees typing (§10.5): `named`, `anonymous` or `off`.
81    #[serde(default, skip_serializing_if = "Patch::is_keep")]
82    pub typing: Patch<TypingMode>,
83    /// New retention.
84    #[serde(default, skip_serializing_if = "Patch::is_keep")]
85    pub retention: Patch<Retention>,
86    /// Re-link to or detach from the parent's overrides.
87    #[serde(default, skip_serializing_if = "Patch::is_keep")]
88    pub sync_with_parent: Patch<bool>,
89    /// New history policy (increments `history_rev`).
90    #[serde(default, skip_serializing_if = "Patch::is_keep")]
91    pub history: Patch<HistoryAccess>,
92    /// Experimental (Appendix A); owner only.
93    #[serde(default, skip_serializing_if = "Patch::is_keep")]
94    pub public_distribution: Patch<bool>,
95    /// Voice channels only: new `user_limit` (1–99); `null` removes it.
96    #[serde(default, skip_serializing_if = "Patch::is_keep")]
97    pub user_limit: Patch<u32>,
98}
99
100/// `channel.delete` (§8.2).
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
102pub struct Delete {
103    /// The channel (or on the envelope).
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub channel_id: Option<ChannelId>,
106}
107
108/// `channel.reorder` (§8.2).
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct Reorder {
111    /// 1–500 entries, each channel at most once.
112    pub positions: Vec<ChannelPosition>,
113}
114
115/// `channel.permissions.update` (§8.2).
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct PermissionsUpdate {
118    /// The channel (or on the envelope).
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub channel_id: Option<ChannelId>,
121    /// Overrides to create or replace.
122    pub set: Vec<Override>,
123    /// Override targets to delete.
124    pub remove: Vec<OverrideTarget>,
125}
126
127pub(crate) fn check_kind(kind: ChannelKind) -> Result<(), BodyError> {
128    match kind {
129        ChannelKind::Category
130        | ChannelKind::Text
131        | ChannelKind::Announcement
132        | ChannelKind::Voice => Ok(()),
133        ChannelKind::Forum => Err(BodyError::unsupported("kind.forum")),
134        ChannelKind::Stage => Err(BodyError::unsupported("kind.stage")),
135        // DMs are opened with `dm.open` (§8.15), never created as channels.
136        ChannelKind::Dm => Err(BodyError::bad("kind", "a dm is opened with dm.open")),
137    }
138}
139
140pub(crate) fn check_user_limit(n: u32) -> Result<(), BodyError> {
141    check::range("user_limit", n, VOICE_USER_LIMIT.0, VOICE_USER_LIMIT.1)
142}
143
144fn check_overrides(field: &str, overrides: &[Override]) -> Result<(), BodyError> {
145    check::count(field, overrides.len(), OVERRIDES_PER_CHANNEL)?;
146    check::unique(field, overrides.iter().map(|o| &o.target))?;
147    overrides.iter().try_for_each(|o| o.check(field))
148}
149
150fn check_history(history: &HistoryAccess) -> Result<(), BodyError> {
151    let (lo, hi) = crate::limits::LAST_N;
152    match *history {
153        HistoryAccess::LastN(n) => check::range("history", n, lo, hi),
154        HistoryAccess::None | HistoryAccess::SinceJoined | HistoryAccess::Full => Ok(()),
155    }
156}
157
158impl Validate for Create {
159    fn validate(&self) -> Result<(), BodyError> {
160        check_kind(self.kind)?;
161        check::text("name", &self.name, CHANNEL_NAME)?;
162        check::opt_text("topic", self.topic.as_deref(), (0, CHANNEL_TOPIC_MAX))?;
163        if self.kind == ChannelKind::Category && self.parent_id.is_some() {
164            return Err(BodyError::bad("parent_id", "a category has no parent"));
165        }
166        if let Some(s) = self.slowmode_s {
167            check::range("slowmode_s", s, 0, SLOWMODE_MAX_S)?;
168        }
169        if let Some(n) = self.user_limit {
170            if self.kind != ChannelKind::Voice {
171                return Err(BodyError::bad("user_limit", "voice channels only"));
172            }
173            check_user_limit(n)?;
174        }
175        check_overrides("overrides", self.overrides.as_deref().unwrap_or_default())?;
176        self.retention.map_or(Ok(()), |r| r.check("retention"))
177    }
178}