use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::addr::Slug;
use crate::api::channels::ChannelType;
use crate::error::{Validate, ValidationError, check_chars};
use crate::external_id::ExternalId;
use crate::id::{Id, parse_id_str};
use crate::limits::NAME_MAX_CHARS;
use super::spaces::{MgmtSpaceMemberRef, check_app_id};
pub const FEATURE_CHANNEL_MEMBER_ADD_REMOVE: &str = "channel_member_add_remove";
pub const CHANNEL_MEMBERS_ADD_MAX: usize = 100;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MgmtMemberRef {
Member(Id),
External(ExternalId),
}
impl FromStr for MgmtMemberRef {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.contains(':') {
return s
.parse()
.map(MgmtMemberRef::External)
.map_err(|e: crate::external_id::ExternalIdError| e.to_string());
}
parse_id_str(s)
.map(MgmtMemberRef::Member)
.ok_or_else(|| format!("{s:?} is neither a member id nor an external id"))
}
}
impl From<ExternalId> for MgmtMemberRef {
fn from(e: ExternalId) -> Self {
MgmtMemberRef::External(e)
}
}
impl fmt::Display for MgmtMemberRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MgmtMemberRef::Member(id) => fmt::Display::fmt(id, f),
MgmtMemberRef::External(e) => fmt::Display::fmt(e, f),
}
}
}
impl Serialize for MgmtMemberRef {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for MgmtMemberRef {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = Cow::<'de, str>::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
impl JsonSchema for MgmtMemberRef {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"MgmtMemberRef".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"maxLength": 128,
"description": "A member id (decimal string) or an external id (k2:principal:<uuid>, k2:workspace:<uuid>, k2:connect:<uuid>, k2:owner or local:<handle>)."
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct MgmtChannelCreateRequest {
pub space_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_id: Option<String>,
pub slug: Slug,
pub name: String,
pub private: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<MgmtMemberRef>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub kind: Option<ChannelType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_limit: Option<u8>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub members_can_leave: bool,
}
impl MgmtChannelCreateRequest {
pub fn new(space_id: Id, slug: Slug, name: impl Into<String>) -> Self {
MgmtChannelCreateRequest {
space_id,
app_id: None,
slug,
name: name.into(),
private: false,
members: Vec::new(),
kind: None,
user_limit: None,
members_can_leave: false,
}
}
}
impl MgmtChannelCreateRequest {
pub fn channel_type(&self) -> ChannelType {
self.kind.unwrap_or(ChannelType::Text)
}
}
impl Validate for MgmtChannelCreateRequest {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(a) = &self.app_id {
check_app_id("app_id", a)?;
}
let kind = self.channel_type();
if !matches!(kind, ChannelType::Text | ChannelType::Voice) {
return Err(ValidationError::invalid(
"type",
"type must be text or voice",
));
}
crate::voice::check_user_limit(self.user_limit)?;
if self.user_limit.is_some() && kind != ChannelType::Voice {
return Err(ValidationError::invalid(
"user_limit",
"user_limit is for voice channels only",
));
}
check_chars("name", &self.name, 1, NAME_MAX_CHARS)?;
if self.members.len() > CHANNEL_MEMBERS_ADD_MAX {
return Err(ValidationError::invalid(
"members",
format!("at most {CHANNEL_MEMBERS_ADD_MAX} members"),
));
}
for (i, m) in self.members.iter().enumerate() {
if self.members[..i].contains(m) {
return Err(ValidationError::invalid(
format!("members.{i}"),
"listed twice",
));
}
}
Ok(())
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum MgmtChannelNotAddedReason {
NotProvisioned = "not_provisioned",
Deactivated = "deactivated",
Assistant = "assistant",
Guest = "guest",
NotSpaceMember = "not_space_member",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelNotAdded {
pub member: MgmtMemberRef,
pub reason: MgmtChannelNotAddedReason,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct MgmtChannelCreateResponse {
pub channel_id: Id,
pub space_id: Id,
pub slug: Slug,
pub name: String,
pub private: bool,
#[serde(rename = "type", default = "text_type")]
pub kind: ChannelType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_limit: Option<u8>,
#[serde(default)]
pub members_can_leave: bool,
pub created: bool,
pub added: Vec<MgmtSpaceMemberRef>,
pub already: Vec<MgmtSpaceMemberRef>,
#[serde(default)]
pub skipped: Vec<Id>,
pub not_added: Vec<MgmtChannelNotAdded>,
}
impl MgmtChannelCreateResponse {
pub fn new(channel_id: Id, space_id: Id, slug: Slug, name: impl Into<String>) -> Self {
MgmtChannelCreateResponse {
channel_id,
space_id,
slug,
name: name.into(),
private: false,
kind: text_type(),
user_limit: None,
members_can_leave: false,
created: false,
added: Vec::new(),
already: Vec::new(),
skipped: Vec::new(),
not_added: Vec::new(),
}
}
}
fn text_type() -> ChannelType {
ChannelType::Text
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelTypeMismatchDetails {
pub reason: String,
pub field: String,
pub existing_type: ChannelType,
}
pub const CHANNEL_BULK_OPS_MAX: usize = 200;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum MgmtChannelOp {
Ensure {
slug: Slug,
name: String,
private: bool,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
kind: Option<ChannelType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
user_limit: Option<u8>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
members_can_leave: bool,
},
Update {
channel_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
members_can_leave: Option<bool>,
},
Rename {
channel_id: Id,
name: String,
},
Archive {
channel_id: Id,
},
Unarchive {
channel_id: Id,
},
}
impl MgmtChannelOp {
pub fn kind(&self) -> MgmtChannelOpKind {
match self {
MgmtChannelOp::Ensure { .. } => MgmtChannelOpKind::Ensure,
MgmtChannelOp::Update { .. } => MgmtChannelOpKind::Update,
MgmtChannelOp::Rename { .. } => MgmtChannelOpKind::Rename,
MgmtChannelOp::Archive { .. } => MgmtChannelOpKind::Archive,
MgmtChannelOp::Unarchive { .. } => MgmtChannelOpKind::Unarchive,
}
}
fn validate_at(&self, i: usize) -> Result<(), ValidationError> {
let at = |e: ValidationError| ValidationError {
field: format!("ops.{i}.{}", e.field),
..e
};
match self {
MgmtChannelOp::Ensure {
name,
kind,
user_limit,
..
} => {
let kind = kind.unwrap_or(ChannelType::Text);
if !matches!(kind, ChannelType::Text | ChannelType::Voice) {
return Err(at(ValidationError::invalid(
"type",
"type must be text or voice",
)));
}
crate::voice::check_user_limit(*user_limit).map_err(at)?;
if user_limit.is_some() && kind != ChannelType::Voice {
return Err(at(ValidationError::invalid(
"user_limit",
"user_limit is for voice channels only",
)));
}
check_chars("name", name, 1, NAME_MAX_CHARS).map_err(at)
}
MgmtChannelOp::Rename { name, .. } => {
check_chars("name", name, 1, NAME_MAX_CHARS).map_err(at)
}
MgmtChannelOp::Update {
members_can_leave, ..
} => {
if members_can_leave.is_none() {
return Err(at(ValidationError::invalid(
"members_can_leave",
"update needs at least one field",
)));
}
Ok(())
}
MgmtChannelOp::Archive { .. } | MgmtChannelOp::Unarchive { .. } => Ok(()),
}
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum MgmtChannelOpKind {
Ensure = "ensure",
Rename = "rename",
Archive = "archive",
Unarchive = "unarchive",
Update = "update",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MgmtChannelBulkRequest {
pub space_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_id: Option<String>,
pub ops: Vec<MgmtChannelOp>,
}
impl Validate for MgmtChannelBulkRequest {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(a) = &self.app_id {
check_app_id("app_id", a)?;
}
if self.ops.is_empty() || self.ops.len() > CHANNEL_BULK_OPS_MAX {
return Err(ValidationError::invalid(
"ops",
format!("1–{CHANNEL_BULK_OPS_MAX} ops"),
));
}
for (i, op) in self.ops.iter().enumerate() {
op.validate_at(i)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelOpResult {
pub op: MgmtChannelOpKind,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<crate::error::ApiError>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MgmtChannelMemberRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_id: Option<String>,
pub external_id: ExternalId,
}
impl Validate for MgmtChannelMemberRequest {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(a) = &self.app_id {
check_app_id("app_id", a)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelMemberResponse {
pub channel_id: Id,
pub space_id: Id,
pub external_id: ExternalId,
pub member_id: Id,
pub changed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MgmtChannelBulkResponse {
pub space_id: Id,
pub results: Vec<MgmtChannelOpResult>,
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn member_ref_parses_both_forms() {
let id: MgmtMemberRef = "48831765147549697".parse().unwrap();
assert!(matches!(id, MgmtMemberRef::Member(_)));
let ext: MgmtMemberRef = "k2:owner".parse().unwrap();
assert_eq!(ext, MgmtMemberRef::External(ExternalId::K2Owner));
for bad in ["", "abc", "k2:nope", "-1"] {
assert!(bad.parse::<MgmtMemberRef>().is_err(), "{bad}");
}
assert_eq!(
serde_json::to_string(&ext).unwrap(),
"\"k2:owner\"".to_owned()
);
}
}