use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::api::files::FileKind;
use crate::error::{Validate, ValidationError};
use crate::id::Id;
use crate::time::Timestamp;
pub const FEATURE_PERSON_NOTIFICATIONS: &str = "person_notifications";
pub const FEATURE_FEED_HEAD: &str = "feed_head";
pub const FEATURE_FEED_ALL_MESSAGES: &str = "feed_all_messages";
pub const FEATURE_PERSON_CHANNEL_NOTIFY: &str = "person_channel_notify";
pub const FEATURE_VOICE_STARTED_FEED: &str = "voice_started_feed";
pub const FEATURE_VOICE_INVITES: &str = "voice_invites";
pub const FEATURE_FEED_ATTACHMENT_INFO: &str = "feed_attachment_info";
pub const PERSON_NOTIFICATIONS_WAIT_MAX_S: u32 = 30;
pub const PERSON_NOTIFICATIONS_LIMIT_DEFAULT: u32 = 100;
pub const PERSON_NOTIFICATIONS_LIMIT_MAX: u32 = 500;
pub const PERSON_NOTIFICATION_PREVIEW_MAX_CHARS: usize = 120;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PersonNotificationsQuery {
pub after: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait: Option<u32>,
}
impl PersonNotificationsQuery {
pub fn limit(&self) -> u32 {
self.limit.unwrap_or(PERSON_NOTIFICATIONS_LIMIT_DEFAULT)
}
pub fn wait_s(&self) -> u32 {
self.wait.unwrap_or(0)
}
}
impl Validate for PersonNotificationsQuery {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(l) = self.limit
&& !(1..=PERSON_NOTIFICATIONS_LIMIT_MAX).contains(&l)
{
return Err(ValidationError::invalid(
"limit",
format!("limit must be 1–{PERSON_NOTIFICATIONS_LIMIT_MAX}"),
));
}
if let Some(w) = self.wait
&& w > PERSON_NOTIFICATIONS_WAIT_MAX_S
{
return Err(ValidationError::invalid(
"wait",
format!("wait must be at most {PERSON_NOTIFICATIONS_WAIT_MAX_S} seconds"),
));
}
Ok(())
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum PersonNotificationKind {
CallRing = "call_ring",
CallMissed = "call_missed",
Mention = "mention",
Dm = "dm",
ReplyToMe = "reply_to_me",
Message = "message",
Keyword = "keyword",
Read = "read",
CallRingStopped = "call_ring_stopped",
VoiceStarted = "voice_started",
VoiceEnded = "voice_ended",
VoiceInvite = "voice_invite",
VoiceInviteStopped = "voice_invite_stopped",
}
}
impl PersonNotificationKind {
pub const fn clears(self) -> bool {
matches!(
self,
PersonNotificationKind::Read
| PersonNotificationKind::CallRingStopped
| PersonNotificationKind::VoiceEnded
| PersonNotificationKind::VoiceInviteStopped
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct PersonNotification {
pub seq: u64,
pub kind: PersonNotificationKind,
pub at: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub space_id: Option<Id>,
pub channel_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_id: Option<Id>,
pub from_member_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from_external_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thread_root_id: Option<Id>,
pub app_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub participant_app_ids: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub invite_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<Timestamp>,
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub attachment_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachment_kinds: Vec<FileKind>,
}
fn is_zero_u32(v: &u32) -> bool {
*v == 0
}
impl PersonNotification {
pub fn new(
kind: PersonNotificationKind,
at: Timestamp,
channel_id: Id,
from_member_id: Id,
) -> Self {
PersonNotification {
seq: 0,
kind,
at,
space_id: None,
channel_id,
message_id: None,
call_id: None,
from_member_id,
from_external_id: None,
thread_root_id: None,
app_id: None,
participant_app_ids: Vec::new(),
preview: None,
invite_id: None,
expires_at: None,
attachment_count: 0,
attachment_kinds: Vec::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct PersonNotificationsPage {
pub items: Vec<PersonNotification>,
pub next: u64,
#[serde(default)]
pub head: u64,
}
impl PersonNotificationsPage {
pub fn new(items: Vec<PersonNotification>, next: u64, head: u64) -> Self {
PersonNotificationsPage { items, next, head }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct PersonNotificationsHead {
pub head: u64,
}
impl PersonNotificationsHead {
pub fn new(head: u64) -> Self {
PersonNotificationsHead { head }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CursorExpiredDetails {
pub oldest_seq: u64,
pub head: u64,
}
pub fn preview_of(body: &str) -> Option<String> {
if body.is_empty() {
return None;
}
Some(
body.chars()
.take(PERSON_NOTIFICATION_PREVIEW_MAX_CHARS)
.collect(),
)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn preview_cut_at_a_char_boundary() {
let s = "é".repeat(300);
let p = preview_of(&s).unwrap();
assert_eq!(p.chars().count(), 120);
assert_eq!(p.len(), 240);
assert_eq!(preview_of("hi").as_deref(), Some("hi"));
assert_eq!(preview_of(""), None);
}
#[test]
fn kind_discriminants_are_fixed() {
use PersonNotificationKind as K;
assert_eq!(K::Unknown as isize, crate::registry::UNKNOWN_DISCRIMINANT);
assert_eq!(
[K::CallRing, K::CallMissed, K::Mention, K::Dm, K::ReplyToMe].map(|k| k as isize),
[0, 1, 2, 3, 4]
);
assert_eq!(
[K::Message, K::Keyword, K::Read, K::CallRingStopped].map(|k| k as isize),
[5, 6, 7, 8]
);
assert_eq!(
[
K::VoiceStarted,
K::VoiceEnded,
K::VoiceInvite,
K::VoiceInviteStopped
]
.map(|k| k as isize),
[9, 10, 11, 12]
);
assert!(K::Read.clears() && K::CallRingStopped.clears());
assert!(K::VoiceEnded.clears() && K::VoiceInviteStopped.clears());
assert!(!K::Mention.clears() && !K::Unknown.clears());
assert!(!K::VoiceStarted.clears() && !K::VoiceInvite.clears());
let k: K = serde_json::from_str("\"voice_invite\"").unwrap();
assert_eq!(k, K::VoiceInvite);
let k: K = serde_json::from_str("\"voice_missed\"").unwrap();
assert_eq!(k, K::Unknown);
}
#[test]
fn page_from_an_older_server_reads() {
let old = r#"{"items": [{"seq": 815, "kind": "mention", "at": "2026-09-27T12:00:01.500Z",
"channel_id": "48831765147549710", "message_id": "48831765147549800",
"from_member_id": "48831765147549703", "app_id": null}], "next": 818}"#;
let page: PersonNotificationsPage = serde_json::from_str(old).unwrap();
assert_eq!((page.next, page.head), (818, 0));
assert_eq!(page.items.len(), 1);
let item = &page.items[0];
assert_eq!(item.kind, PersonNotificationKind::Mention);
assert_eq!((&item.from_external_id, item.thread_root_id), (&None, None));
let empty: PersonNotificationsPage =
serde_json::from_str(r#"{"items": [], "next": 77}"#).unwrap();
assert_eq!(empty, PersonNotificationsPage::new(Vec::new(), 77, 0));
}
#[test]
fn item_wire_shape() {
let mut i = PersonNotification::new(
PersonNotificationKind::Read,
Timestamp::from_unix_ms_saturating(0),
Id::from_i64(2).unwrap(),
Id::from_i64(3).unwrap(),
);
i.seq = 9;
let v = serde_json::to_value(&i).unwrap();
for absent in ["from_external_id", "thread_root_id", "preview", "space_id"] {
assert!(v.get(absent).is_none(), "{v}");
}
assert!(v["app_id"].is_null(), "{v}");
i.thread_root_id = Id::from_i64(5);
i.from_external_id = Some("local:bob".into());
let v = serde_json::to_value(&i).unwrap();
assert_eq!(v["thread_root_id"], "5");
assert_eq!(v["from_external_id"], "local:bob");
let back: PersonNotification = serde_json::from_value(v).unwrap();
assert_eq!(back, i);
}
#[test]
fn voice_items_wire_shape() {
let mut i = PersonNotification::new(
PersonNotificationKind::VoiceInvite,
Timestamp::from_unix_ms_saturating(1_000),
Id::from_i64(2).unwrap(),
Id::from_i64(3).unwrap(),
);
i.seq = 903;
i.space_id = Id::from_i64(7);
i.invite_id = Id::from_i64(9);
i.expires_at = Some(Timestamp::from_unix_ms_saturating(301_000));
let v = serde_json::to_value(&i).unwrap();
assert_eq!(v["kind"], "voice_invite");
assert_eq!(v["invite_id"], "9");
assert_eq!(v["expires_at"], "1970-01-01T00:05:01.000Z");
for absent in ["message_id", "call_id", "thread_root_id", "preview"] {
assert!(v.get(absent).is_none(), "{v}");
}
let back: PersonNotification = serde_json::from_value(v).unwrap();
assert_eq!(back, i);
let old = r#"{"seq": 5, "kind": "mention", "at": "2026-09-27T12:00:01.500Z",
"channel_id": "2", "from_member_id": "3", "app_id": null}"#;
let old: PersonNotification = serde_json::from_str(old).unwrap();
assert_eq!((old.invite_id, old.expires_at), (None, None));
let started = PersonNotification::new(
PersonNotificationKind::VoiceStarted,
Timestamp::from_unix_ms_saturating(0),
Id::from_i64(2).unwrap(),
Id::from_i64(3).unwrap(),
);
let v = serde_json::to_value(&started).unwrap();
for absent in ["invite_id", "expires_at", "message_id"] {
assert!(v.get(absent).is_none(), "{v}");
}
}
#[test]
fn attachment_info_wire_shape() {
let mut i = PersonNotification::new(
PersonNotificationKind::Dm,
Timestamp::from_unix_ms_saturating(0),
Id::from_i64(2).unwrap(),
Id::from_i64(3).unwrap(),
);
let v = serde_json::to_value(&i).unwrap();
for absent in ["attachment_count", "attachment_kinds"] {
assert!(v.get(absent).is_none(), "{v}");
}
i.attachment_count = 3;
i.attachment_kinds = vec![FileKind::Image, FileKind::Document];
let v = serde_json::to_value(&i).unwrap();
assert_eq!(v["attachment_count"], 3);
assert_eq!(
v["attachment_kinds"],
serde_json::json!(["image", "document"])
);
let back: PersonNotification = serde_json::from_value(v).unwrap();
assert_eq!(back, i);
let old = r#"{"seq": 5, "kind": "dm", "at": "2026-09-27T12:00:01.500Z",
"channel_id": "2", "from_member_id": "3", "app_id": null}"#;
let old: PersonNotification = serde_json::from_str(old).unwrap();
assert_eq!(old.attachment_count, 0);
assert!(old.attachment_kinds.is_empty());
let new = r#"{"seq": 5, "kind": "dm", "at": "2026-09-27T12:00:01.500Z",
"channel_id": "2", "from_member_id": "3", "app_id": null,
"attachment_count": 2, "attachment_kinds": ["model", "image"]}"#;
let new: PersonNotification = serde_json::from_str(new).unwrap();
assert_eq!(
new.attachment_kinds,
vec![FileKind::Unknown, FileKind::Image]
);
}
#[test]
fn query_bounds() {
let q = |limit, wait| PersonNotificationsQuery {
after: 0,
limit,
wait,
};
assert!(q(None, None).validate().is_ok());
assert!(q(Some(500), Some(30)).validate().is_ok());
assert!(q(Some(0), None).validate().is_err());
assert!(q(Some(501), None).validate().is_err());
assert!(q(None, Some(31)).validate().is_err());
assert_eq!((q(None, None).limit(), q(None, None).wait_s()), (100, 0));
}
}