use serde::{Deserialize, Serialize};
use crate::{ActionKind, Answer, Grant, GrantId, Grantee, KindSet, Lifetime, Role, TreePath};
pub const VISITOR_ENTRY_APP: &str = "so.tilo.lang.entry";
pub const VISITOR_ENTRY_ACTIONS: [&str; 3] = ["join", "confirm", "leave"];
pub const MAX_DESCRIPTION_CHARS: usize = 280;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListingPolicy {
pub description: String,
pub default_role: Role,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EntryError {
Description,
Role,
Contact,
Mail,
}
impl std::fmt::Display for EntryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Description => write!(
f,
"a description is at most {MAX_DESCRIPTION_CHARS} characters of text"
),
Self::Role => {
f.write_str("people who join on their own become viewers, commenters or editors")
}
Self::Contact => f.write_str(
"a wait list's contact is at most 280 characters, without control characters",
),
Self::Mail => f.write_str(
"a wait list mails from a sender (`hello@example.com`) without control characters",
),
}
}
}
impl std::error::Error for EntryError {}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryPolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub listing: Option<ListingPolicy>,
#[serde(default, skip_serializing_if = "is_false")]
pub invitation_only: bool,
#[serde(default, skip_serializing_if = "is_zero")]
pub wait_list_max: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contact: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mail: Option<EntryMail>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EntryMail {
pub from: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub templates: Option<String>,
}
impl EntryPolicy {
#[must_use]
pub const fn is_listed(&self) -> bool {
self.listing.is_some()
}
#[must_use]
pub const fn keeps_requests(&self) -> bool {
self.invitation_only && self.wait_list_max > 0
}
#[must_use]
pub const fn open_role(&self) -> Option<Role> {
match &self.listing {
Some(listing) if !self.invitation_only => Some(listing.default_role),
_ => None,
}
}
#[must_use]
pub fn visitor_grants(&self, workspace: &str) -> Vec<Grant> {
if !self.keeps_requests() {
return Vec::new();
}
VISITOR_ENTRY_ACTIONS
.into_iter()
.map(|action| Grant {
id: GrantId::new(format!("entry:visitor:{action}")),
grantee: Grantee::AnyKey,
node: TreePath::workspace(workspace)
.app(VISITOR_ENTRY_APP)
.rest()
.action(action),
kinds: KindSet::of(ActionKind::Read).with(ActionKind::Undoable),
answer: Answer::Allow,
lifetime: Lifetime::UntilRevoked,
granted_by: Grantee::role(Role::Owner),
})
.collect()
}
pub fn checked(self) -> Result<Self, EntryError> {
let listing = match self.listing {
Some(listing) => {
let description = listing.description.trim().to_owned();
if description.chars().count() > MAX_DESCRIPTION_CHARS
|| description.chars().any(|c| c.is_control() && c != '\n')
{
return Err(EntryError::Description);
}
if !Role::Editor.includes(listing.default_role) {
return Err(EntryError::Role);
}
Some(ListingPolicy {
description,
default_role: listing.default_role,
})
}
None => None,
};
let contact = self
.contact
.map(|contact| contact.trim().to_owned())
.filter(|contact| !contact.is_empty());
if let Some(contact) = &contact
&& (contact.chars().count() > MAX_DESCRIPTION_CHARS
|| contact.chars().any(char::is_control))
{
return Err(EntryError::Contact);
}
let mail = match self.mail {
None => None,
Some(mail) => {
let from = mail.from.trim().to_owned();
if from.is_empty() || !from.contains('@') || from.chars().any(char::is_control) {
return Err(EntryError::Mail);
}
let templates = mail
.templates
.map(|templates| templates.trim().to_owned())
.filter(|templates| !templates.is_empty());
Some(EntryMail { from, templates })
}
};
Ok(Self {
listing,
contact,
mail,
..self
})
}
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if takes the field by reference"
)]
const fn is_false(value: &bool) -> bool {
!*value
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if takes the field by reference"
)]
const fn is_zero(value: &usize) -> bool {
*value == 0
}