//! Registered chat channels: which ones the bot may read or write, and message splitting. use crate::settings::ChatChannelSettings; use std::collections::HashMap; /// Discord's message length limit, in UTF-16 code units as Discord counts. pub const MESSAGE_LIMIT: usize = 2000; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ChatMessage { pub channel_id: u64, pub message_id: u64, pub author_id: u64, pub author_name: String, pub author_is_bot: bool, /// Written by this bot. Live events never carry these; history reads do. pub from_self: bool, /// What the person wrote. Data, never instructions (privacy.md). pub content: String, /// RFC 3339. pub created_at: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ChatAccessError(pub String); impl std::fmt::Display for ChatAccessError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::error::Error for ChatAccessError {} pub struct ChatChannels { by_id: HashMap, } impl ChatChannels { pub fn new(channels: &[ChatChannelSettings]) -> Self { Self { by_id: channels.iter().map(|c| (c.id, c.clone())).collect() } } /// Some channel is readable, so the bot needs the message intents. pub fn any_readable(&self) -> bool { self.by_id.values().any(|c| c.read) } pub fn can_read(&self, id: u64) -> bool { self.by_id.get(&id).is_some_and(|c| c.read) } pub fn can_send(&self, id: u64) -> bool { self.by_id.get(&id).is_some_and(|c| c.send) } pub fn check_read(&self, id: u64) -> Result<(), ChatAccessError> { match self.by_id.get(&id) { None => Err(ChatAccessError(format!("channel {id} is not a registered chat channel"))), Some(c) if !c.read => Err(ChatAccessError(format!("reading channel {id} is turned off"))), Some(_) => Ok(()), } } pub fn check_send(&self, id: u64) -> Result<(), ChatAccessError> { match self.by_id.get(&id) { None => Err(ChatAccessError(format!("channel {id} is not a registered chat channel"))), Some(c) if !c.send => Err(ChatAccessError(format!("sending to channel {id} is turned off"))), Some(_) => Ok(()), } } /// The switch a chat action needs (`send`, `edit`, `react`, `delete`, `pin`, `unpin`). pub fn check_action(&self, id: u64, action: &str) -> Result<(), ChatAccessError> { let Some(c) = self.by_id.get(&id) else { return Err(ChatAccessError(format!("channel {id} is not a registered chat channel"))); }; let on = match action { "send" => c.send, "edit" => c.edit, "react" => c.react, "delete" => c.delete, "pin" | "unpin" => c.pin, _ => return Err(ChatAccessError(format!("unknown chat action {action}"))), }; if on { Ok(()) } else { Err(ChatAccessError(format!("{action} is turned off for channel {id}"))) } } pub fn all(&self) -> impl Iterator { self.by_id.values() } } /// Split text into messages of at most `limit` UTF-16 units, breaking at the last newline, else the /// last space, else hard (never inside a character). Nothing is lost except the newline or space a /// break happens at. pub fn split_message(text: &str, limit: usize) -> Vec { let mut out = Vec::new(); let mut rest = text; loop { // Byte offset just past the longest prefix within the limit, and whether more follows. let mut units = 0; let mut cut = rest.len(); let mut window_end = rest.len(); // the prefix plus one more character, to see a break right at the limit for (i, ch) in rest.char_indices() { if units + ch.len_utf16() > limit { cut = i; window_end = i + ch.len_utf8(); break; } units += ch.len_utf16(); } if cut == rest.len() { if !rest.is_empty() { out.push(rest.to_owned()); } return out; } let window = &rest[..window_end]; let brk = window.rfind('\n').filter(|&b| b > 0).or_else(|| window.rfind(' ').filter(|&b| b > 0)); match brk { Some(b) => { out.push(rest[..b].to_owned()); rest = &rest[b + 1..]; } None => { out.push(rest[..cut].to_owned()); rest = &rest[cut..]; } } } } /// Message Content intent bits in the application flags (GATEWAY_MESSAGE_CONTENT and its _LIMITED form). pub fn has_message_content_intent(application_flags: u64) -> bool { application_flags & ((1 << 18) | (1 << 19)) != 0 } #[cfg(test)] mod tests { use super::*; fn utf16_len(s: &str) -> usize { s.encode_utf16().count() } #[test] fn short_text_is_left_alone() { assert_eq!(split_message("안녕하세요", MESSAGE_LIMIT), vec!["안녕하세요"]); assert!(split_message("", MESSAGE_LIMIT).is_empty()); } #[test] fn breaks_at_the_last_newline_then_space_and_loses_only_the_break() { assert_eq!(split_message("aaaa bbbb\ncccc dddd", 12), vec!["aaaa bbbb", "cccc dddd"]); assert_eq!(split_message("aaaa bbbb cccc", 10), vec!["aaaa bbbb", "cccc"]); // A break exactly at the limit is used. assert_eq!(split_message("aaaa bbbb", 4), vec!["aaaa", "bbbb"]); } #[test] fn hard_cuts_keep_emoji_whole() { let text = format!("{}😀y", "x".repeat(MESSAGE_LIMIT - 1)); let parts = split_message(&text, MESSAGE_LIMIT); assert!(parts.iter().all(|p| utf16_len(p) <= MESSAGE_LIMIT)); assert_eq!(parts.concat(), text); assert!(parts[1].starts_with('😀')); } #[test] fn every_part_fits_for_long_mixed_text() { let text: Vec = (0..900).map(|i| format!("줄 {i} 내용입니다")).collect(); let text = text.join("\n"); let parts = split_message(&text, MESSAGE_LIMIT); assert!(parts.len() > 1); assert!(parts.iter().all(|p| !p.is_empty() && utf16_len(p) <= MESSAGE_LIMIT)); assert_eq!(parts.join("\n"), text); } fn ch(id: u64, read: bool, send: bool) -> ChatChannelSettings { ChatChannelSettings { id, name: String::new(), description: String::new(), read, send, edit: true, react: true, delete: false, pin: false, answer_all: false, sync_discord: true } } #[test] fn each_action_needs_its_own_switch() { let mut open = ch(1, true, true); open.delete = true; let c = ChatChannels::new(&[open, ch(2, true, false)]); for a in ["send", "edit", "react", "delete"] { assert!(c.check_action(1, a).is_ok(), "{a}"); } assert!(c.check_action(1, "pin").is_err() && c.check_action(1, "unpin").is_err()); assert!(c.check_action(2, "send").is_err() && c.check_action(2, "delete").is_err()); assert!(c.check_action(2, "react").is_ok()); assert!(c.check_action(3, "send").unwrap_err().0.contains("not a registered")); assert!(c.check_action(1, "explode").is_err()); } #[test] fn each_channel_follows_its_switches_and_strangers_are_refused() { let c = ChatChannels::new(&[ch(1, true, false), ch(2, false, true)]); assert!(c.can_read(1) && !c.can_send(1) && !c.can_read(2) && c.can_send(2)); assert!(c.check_send(1).is_err() && c.check_read(2).is_err()); assert!(c.check_read(3).unwrap_err().0.contains("not a registered")); assert!(c.any_readable()); assert!(!ChatChannels::new(&[ch(2, false, true)]).any_readable()); } #[test] fn message_content_intent_full_or_limited() { assert!(has_message_content_intent(1 << 18)); assert!(has_message_content_intent(1 << 19)); assert!(!has_message_content_intent((1 << 15) | (1 << 13))); } }