//! Chat channel names and topics kept in step with Discord (`app/src/admin.spec.md`, "Chat channel //! names and topics"; `docs/v2/conversation.md`, "채널 이름·주제 반영"). When the chat channel //! settings are saved, each channel with `syncDiscord` whose name or description changed gets them as //! its Discord name and topic; Discord's own form of the name (spaces become `-`) is written back. //! Discord allows only a few such edits per channel in ten minutes: a refused edit is "pending" and //! tried again by itself after the wait Discord names. Without the permission (or any other refusal) //! the edit is "failed" with the reason, and the app keeps what the user wrote. use std::collections::HashMap; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; use async_trait::async_trait; use serde::Serialize; use serde_json::{json, Value}; use crate::settings::ChatChannelSettings; /// Discord's limit for a channel topic. pub const TOPIC_MAX: usize = 1024; #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct ChannelInfo { pub name: String, pub topic: String, } #[derive(Debug, Clone, PartialEq)] pub enum ApiError { /// Too many edits: try again after this long. RateLimited(Duration), Failed(String), } /// Discord's channel endpoints (a fake in tests). #[async_trait] pub trait ChannelApi: Send + Sync { async fn info(&self, id: u64) -> Result; /// Set what is given; returns the channel as Discord stored it. async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result; } #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(tag = "state", rename_all = "camelCase")] pub enum SyncState { Applied { name: String }, #[serde(rename_all = "camelCase")] Pending { retry_in_sec: u64 }, Failed { reason: String }, } /// Refuse (before anything is saved) a description Discord would not take as a topic. pub fn check_topics(channels: &[ChatChannelSettings]) -> Result<(), String> { match channels.iter().find(|c| c.sync_discord && c.description.chars().count() > TOPIC_MAX) { Some(c) => Err(format!("채널 {}의 설명이 {}자를 넘어 디스코드 주제로 쓸 수 없습니다 ({}자)", c.id, TOPIC_MAX, c.description.chars().count())), None => Ok(()), } } /// The channels to bring to Discord after a save: `syncDiscord` on and new, or with another name or /// description than before. pub fn changed(old: &[ChatChannelSettings], new: &[ChatChannelSettings]) -> Vec { new.iter().filter(|c| c.sync_discord) .filter(|c| old.iter().find(|o| o.id == c.id) .is_none_or(|o| o.name != c.name || o.description != c.description || !o.sync_discord)) .cloned().collect() } pub struct Syncer { api: Arc, settings_file: PathBuf, status: Mutex>, /// Channels with a retry already waiting (another save while waiting adds none), and whether /// that channel was new (so the retry still keeps empty fields out). retrying: Mutex>, /// One channel edit at a time: a later save waits for an earlier one, so a slow answer to the /// earlier never lands after the later. edit_lock: tokio::sync::Mutex<()>, } impl Syncer { pub fn new(api: Arc, settings_file: PathBuf) -> Arc { Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default(), edit_lock: tokio::sync::Mutex::new(()) }) } /// A channel's name and topic on Discord now (the screens fill a newly registered channel with them). pub async fn info(&self, id: u64) -> Result { self.api.info(id).await.map_err(|e| match e { ApiError::RateLimited(w) => format!("디스코드가 {}초 뒤에 다시 물어 달라고 합니다", w.as_secs()), ApiError::Failed(r) => r, }) } pub fn status(&self) -> HashMap { self.status.lock().unwrap().clone() } /// Bring these channels to Discord now; `old` tells which ones are new (a new one never clears a /// Discord name or topic with an empty field). pub async fn sync(self: &Arc, channels: Vec, old: &[ChatChannelSettings]) -> Vec<(u64, SyncState)> { let mut out = vec![]; for c in channels { let is_new = !old.iter().any(|o| o.id == c.id); let state = self.sync_one(&c, is_new).await; self.status.lock().unwrap().insert(c.id, state.clone()); out.push((c.id, state)); } out } async fn sync_one(self: &Arc, c: &ChatChannelSettings, is_new: bool) -> SyncState { let _one_at_a_time = self.edit_lock.lock().await; let current = match self.api.info(c.id).await { Ok(i) => i, Err(e) => return self.refused(c.id, e, is_new), }; let keep = |v: &str| !(is_new && v.trim().is_empty()); let name = (keep(&c.name) && c.name != current.name).then_some(c.name.as_str()); let topic = (keep(&c.description) && c.description != current.topic).then_some(c.description.as_str()); if name.is_none() && topic.is_none() { return SyncState::Applied { name: current.name }; } match self.api.edit(c.id, name, topic).await { Ok(stored) => { if keep(&c.name) && stored.name != c.name { self.write_name(c.id, &c.name, &stored.name); } crate::info_log!("chat", "channel {} name and topic updated on Discord", c.id); SyncState::Applied { name: stored.name } } Err(e) => self.refused(c.id, e, is_new), } } fn refused(self: &Arc, id: u64, e: ApiError, is_new: bool) -> SyncState { match e { ApiError::RateLimited(wait) => { crate::info_log!("chat", "channel {id}: Discord asks to wait {}s before the next edit", wait.as_secs()); let first = { let mut r = self.retrying.lock().unwrap(); let first = !r.contains_key(&id); *r.entry(id).or_insert(is_new) |= is_new; first }; if first { let me = self.clone(); tokio::spawn(async move { tokio::time::sleep(wait).await; let is_new = me.retrying.lock().unwrap().remove(&id).unwrap_or(false); me.retry(id, is_new).await; }); } SyncState::Pending { retry_in_sec: wait.as_secs().max(1) } } ApiError::Failed(reason) => { crate::warn_log!("chat", "channel {id}: name and topic not updated on Discord: {reason}"); SyncState::Failed { reason } } } } /// Try a pending channel again with what the settings hold now. async fn retry(self: &Arc, id: u64, is_new: bool) { let Ok(settings) = crate::settings::load_settings(&self.settings_file) else { return }; match settings.chat_channels.into_iter().find(|c| c.id == id && c.sync_discord) { Some(c) => { let state = self.sync_one(&c, is_new).await; self.status.lock().unwrap().insert(id, state); } None => { self.status.lock().unwrap().remove(&id); } } } /// Show Discord's form of the name (spaces become `-`) in the app too, only while the settings /// still hold the name that was sent (a later save keeps its own). fn write_name(&self, id: u64, sent: &str, name: &str) { let Ok(view) = crate::settings_edit::view(&self.settings_file) else { return }; let Some(Value::Array(mut list)) = view.get("chatChannels").cloned() else { return }; let mut changed = false; for c in &mut list { if c["id"].as_str() == Some(id.to_string().as_str()) && c["name"].as_str() == Some(sent) { c["name"] = json!(name); changed = true; } } if !changed { return; } let mut changes = serde_json::Map::new(); changes.insert("chatChannels".into(), Value::Array(list)); if let Err(e) = crate::settings_edit::apply(&self.settings_file, &changes) { crate::warn_log!("chat", "channel {id}: could not write Discord's name back: {}", e.0); } } } /// Discord's REST API with the stored bot token. Serenity's client waits out rate limits by itself /// (up to ten minutes for channel edits), so these two calls go out directly and report the wait. pub struct DiscordRest { pub secrets_file: PathBuf, pub base: String, } impl DiscordRest { pub fn new(secrets_file: PathBuf) -> Self { Self { secrets_file, base: "https://discord.com/api/v10".into() } } async fn call(&self, req: impl FnOnce(&reqwest::Client, String) -> reqwest::RequestBuilder) -> Result { let token = crate::secrets::Secrets::new(&self.secrets_file).get(crate::secrets::DISCORD_TOKEN) .ok().flatten().ok_or_else(|| ApiError::Failed("봇 토큰이 저장되어 있지 않습니다".into()))?; let client = reqwest::Client::builder().timeout(Duration::from_secs(15)).build() .map_err(|e| ApiError::Failed(e.to_string()))?; let r = req(&client, self.base.clone()).header("Authorization", format!("Bot {token}")) .header("User-Agent", "DiscordBot (https://github.com/jarvis, 0.1)").send().await .map_err(|e| ApiError::Failed(format!("디스코드에 연결하지 못했습니다: {e}")))?; let status = r.status().as_u16(); let body: Value = serde_json::from_str(&r.text().await.unwrap_or_default()).unwrap_or_default(); match status { 200..=299 => Ok(ChannelInfo { name: body["name"].as_str().unwrap_or_default().to_owned(), topic: body["topic"].as_str().unwrap_or_default().to_owned() }), 429 => Err(ApiError::RateLimited(Duration::from_secs_f64(body["retry_after"].as_f64().unwrap_or(60.0).ceil()))), 403 => Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into())), 404 => Err(ApiError::Failed("디스코드에서 이 채널을 찾지 못했습니다".into())), _ => Err(ApiError::Failed(format!("디스코드가 거절했습니다 ({status}): {}", body["message"].as_str().unwrap_or_default()))), } } } #[async_trait] impl ChannelApi for DiscordRest { async fn info(&self, id: u64) -> Result { self.call(|c, base| c.get(format!("{base}/channels/{id}"))).await } async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result { let mut body = serde_json::Map::new(); if let Some(n) = name { body.insert("name".into(), json!(n)); } if let Some(t) = topic { body.insert("topic".into(), json!(t)); } let body = Value::Object(body).to_string(); self.call(move |c, base| c.patch(format!("{base}/channels/{id}")) .header("Content-Type", "application/json").body(body)).await } } #[cfg(test)] mod tests { use super::*; use crate::datadir::temp_dir; /// Discord as the tests need it: names lose their spaces, a channel may refuse, and the first /// `limited` edits are rate limited. #[derive(Default)] struct FakeDiscord { channels: Mutex>, forbidden: Vec, limited: Mutex, edits: Mutex, Option)>>, /// How long each next edit takes (the first save's slow answer). delays: Mutex>, } #[async_trait] impl ChannelApi for FakeDiscord { async fn info(&self, id: u64) -> Result { self.channels.lock().unwrap().get(&id).cloned().ok_or_else(|| ApiError::Failed("없음".into())) } async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result { if self.forbidden.contains(&id) { return Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into())); } let delay = { let mut d = self.delays.lock().unwrap(); if d.is_empty() { None } else { Some(d.remove(0)) } }; if let Some(d) = delay { tokio::time::sleep(d).await; } { let mut l = self.limited.lock().unwrap(); if *l > 0 { *l -= 1; return Err(ApiError::RateLimited(Duration::from_millis(200))); } } self.edits.lock().unwrap().push((id, name.map(String::from), topic.map(String::from))); let mut chans = self.channels.lock().unwrap(); let c = chans.get_mut(&id).unwrap(); if let Some(n) = name { c.name = n.replace(' ', "-"); } if let Some(t) = topic { c.topic = t.into(); } Ok(c.clone()) } } const A: u64 = 100000000000000001; const B: u64 = 100000000000000002; fn ch(id: u64, name: &str, description: &str) -> ChatChannelSettings { ChatChannelSettings { id, name: name.into(), description: description.into(), read: true, send: true, edit: true, react: true, delete: false, pin: false, answer_all: false, sync_discord: true } } fn fake(forbidden: Vec, limited: u32) -> Arc { let f = FakeDiscord { forbidden, limited: Mutex::new(limited), ..Default::default() }; f.channels.lock().unwrap().insert(A, ChannelInfo { name: "일정".into(), topic: "".into() }); f.channels.lock().unwrap().insert(B, ChannelInfo { name: "잡담".into(), topic: "아무 말".into() }); Arc::new(f) } fn settings_with(chans: &[ChatChannelSettings]) -> PathBuf { let f = temp_dir("sync").join("settings.json"); std::fs::create_dir_all(f.parent().unwrap()).unwrap(); let list: Vec = chans.iter().map(|c| json!({"id": c.id.to_string(), "name": c.name, "description": c.description})).collect(); std::fs::write(&f, json!({"chatChannels": list}).to_string()).unwrap(); f } #[test] fn only_new_or_edited_channels_that_keep_discord_in_step_are_sent() { let old = vec![ch(A, "일정", ""), ch(B, "잡담", "아무 말")]; let mut off = ch(B, "잡담2", "아무 말"); off.sync_discord = false; assert!(changed(&old, &old).is_empty()); assert_eq!(changed(&old, &[ch(A, "일정 표", ""), off]).iter().map(|c| c.id).collect::>(), [A]); assert_eq!(changed(&[], &[ch(B, "잡담", "아무 말")]).len(), 1, "a newly registered channel"); } #[test] fn a_topic_over_discord_s_limit_is_refused_before_saving() { let long = "가".repeat(TOPIC_MAX + 1); assert!(check_topics(&[ch(A, "일정", &long)]).unwrap_err().contains("1024")); let mut off = ch(A, "일정", &long); off.sync_discord = false; assert!(check_topics(&[off]).is_ok(), "not sent to Discord: any length"); } #[tokio::test] async fn an_edit_reaches_discord_and_discord_s_form_of_the_name_comes_back() { let d = fake(vec![], 0); let file = settings_with(&[ch(A, "일정 표", "할 일")]); let s = Syncer::new(d.clone(), file.clone()); let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[ch(A, "일정", "")]).await; assert_eq!(out, [(A, SyncState::Applied { name: "일정-표".into() })]); assert_eq!(d.channels.lock().unwrap()[&A], ChannelInfo { name: "일정-표".into(), topic: "할 일".into() }); let saved = crate::settings::load_settings(&file).unwrap(); assert_eq!(saved.chat_channels[0].name, "일정-표", "the app shows Discord's name"); } #[tokio::test] async fn without_permission_it_fails_with_the_reason_and_the_app_keeps_the_text() { let d = fake(vec![A], 0); let file = settings_with(&[ch(A, "일정 표", "할 일")]); let s = Syncer::new(d.clone(), file.clone()); let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[]).await; assert!(matches!(&out[0].1, SyncState::Failed { reason } if reason.contains("권한")), "{out:?}"); assert_eq!(crate::settings::load_settings(&file).unwrap().chat_channels[0].name, "일정 표"); assert_eq!(d.channels.lock().unwrap()[&A].name, "일정"); } #[tokio::test] async fn a_rate_limited_edit_is_pending_and_goes_through_by_itself_with_the_latest_text() { let d = fake(vec![], 1); let file = settings_with(&[ch(A, "일정 표", "할 일")]); let s = Syncer::new(d.clone(), file.clone()); let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[ch(A, "일정", "")]).await; assert!(matches!(out[0].1, SyncState::Pending { .. }), "{out:?}"); // Edited again while waiting: the retry sends what the settings hold then. std::fs::write(&file, json!({"chatChannels": [{"id": A.to_string(), "name": "일정 표 2", "description": "할 일"}]}) .to_string()).unwrap(); // A second save while waiting is pending too, but adds no second retry. *d.limited.lock().unwrap() = 1; let again = s.sync(vec![ch(A, "일정 표 2", "할 일")], &[ch(A, "일정 표", "할 일")]).await; assert!(matches!(again[0].1, SyncState::Pending { .. }), "{again:?}"); tokio::time::sleep(Duration::from_millis(500)).await; assert_eq!(s.status()[&A], SyncState::Applied { name: "일정-표-2".into() }); assert_eq!(d.channels.lock().unwrap()[&A].name, "일정-표-2"); assert_eq!(d.edits.lock().unwrap().len(), 1, "one retry, one edit"); } #[tokio::test] async fn a_new_channel_with_empty_fields_never_clears_discord_and_unchanged_ones_are_not_edited() { let d = fake(vec![], 0); let s = Syncer::new(d.clone(), settings_with(&[])); let out = s.sync(vec![ch(B, "", "")], &[]).await; assert_eq!(out, [(B, SyncState::Applied { name: "잡담".into() })]); assert_eq!(d.channels.lock().unwrap()[&B].topic, "아무 말"); s.sync(vec![ch(B, "잡담", "아무 말")], &[]).await; assert!(d.edits.lock().unwrap().is_empty(), "nothing differs from Discord: no edit"); } #[tokio::test] async fn a_retried_new_channel_still_never_clears_discord_with_an_empty_field() { let d = fake(vec![], 1); let file = settings_with(&[ch(B, "잡담 2", "")]); let s = Syncer::new(d.clone(), file); let out = s.sync(vec![ch(B, "잡담 2", "")], &[]).await; assert!(matches!(out[0].1, SyncState::Pending { .. }), "{out:?}"); tokio::time::sleep(Duration::from_millis(500)).await; assert_eq!(s.status()[&B], SyncState::Applied { name: "잡담-2".into() }); assert_eq!(d.channels.lock().unwrap()[&B].topic, "아무 말", "the retry kept the empty description out"); } #[tokio::test] async fn a_slow_first_save_never_overwrites_a_later_one() { let d = fake(vec![], 0); *d.delays.lock().unwrap() = vec![Duration::from_millis(300)]; let file = settings_with(&[ch(A, "일정 표", "")]); let s = Syncer::new(d.clone(), file.clone()); let s1 = s.clone(); let first = tokio::spawn(async move { s1.sync(vec![ch(A, "일정 표", "")], &[ch(A, "일정", "")]).await }); tokio::time::sleep(Duration::from_millis(50)).await; // Saved again while Discord still answers the first edit. std::fs::write(&file, json!({"chatChannels": [{"id": A.to_string(), "name": "회의", "description": ""}]}).to_string()).unwrap(); s.sync(vec![ch(A, "회의", "")], &[ch(A, "일정 표", "")]).await; first.await.unwrap(); assert_eq!(d.channels.lock().unwrap()[&A].name, "회의", "Discord ends with the later save"); assert_eq!(crate::settings::load_settings(&file).unwrap().chat_channels[0].name, "회의", "and so does the app"); } }