wabot_addon_chat_controller_cmd/
lib.rs1use std::path::PathBuf;
13use std::sync::Arc;
14
15use async_trait::async_trait;
16use parking_lot::Mutex;
17use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
18use tokio::sync::Notify;
19
20use wabot_feature_chat_controller::{
21 ChannelError, ChannelMessage, ChatChannel, ChatConnection, ChatMessage, ChatType,
22 MessageCallback, ReplyResult,
23};
24
25pub const CMD_CHANNEL_NAME: &str = "CmdChannel";
26
27const CHAT_ID_PATH: &str = ".cmd-channel/id.json";
28
29pub struct CmdChannel {
32 inner: Arc<Inner>,
33}
34
35struct Inner {
36 callback: Mutex<Option<MessageCallback>>,
37 chat_id: Mutex<Option<String>>,
38 shutdown: Notify,
40}
41
42impl Default for CmdChannel {
43 fn default() -> Self {
44 Self {
45 inner: Arc::new(Inner {
46 callback: Mutex::new(None),
47 chat_id: Mutex::new(None),
48 shutdown: Notify::new(),
49 }),
50 }
51 }
52}
53
54impl CmdChannel {
55 pub fn new() -> Self {
56 Self::default()
57 }
58
59 fn ensure_chat_id(&self) -> String {
60 let mut slot = self.inner.chat_id.lock();
61 if let Some(id) = slot.as_ref() {
62 return id.clone();
63 }
64 let id = match std::fs::read_to_string(CHAT_ID_PATH) {
65 Ok(content) => match serde_json::from_str::<String>(content.trim()) {
66 Ok(id) => id,
67 Err(_) => mint_chat_id_to_disk(),
68 },
69 Err(_) => mint_chat_id_to_disk(),
70 };
71 *slot = Some(id.clone());
72 id
73 }
74}
75
76fn mint_chat_id_to_disk() -> String {
77 let id = format!("cmd-{}", &uuid_like());
78 let path = PathBuf::from(CHAT_ID_PATH);
79 if let Some(parent) = path.parent() {
80 let _ = std::fs::create_dir_all(parent);
81 }
82 let _ = std::fs::write(&path, serde_json::to_string(&id).unwrap_or_default());
83 id
84}
85
86fn uuid_like() -> String {
87 use std::time::{SystemTime, UNIX_EPOCH};
88 let nanos = SystemTime::now()
89 .duration_since(UNIX_EPOCH)
90 .map(|d| d.as_nanos())
91 .unwrap_or(0);
92 format!("{nanos:x}")
93}
94
95#[async_trait]
96impl ChatChannel for CmdChannel {
97 fn listen(&self, callback: MessageCallback) {
98 *self.inner.callback.lock() = Some(callback);
99 }
100
101 async fn connect(&self) -> Result<(), ChannelError> {
102 let stdin = tokio::io::stdin();
103 let mut reader = BufReader::new(stdin).lines();
104 let mut stdout = tokio::io::stdout();
105
106 let _ = stdout
107 .write_all(b"[wabot] CmdChannel ready. Type 'exit' to quit.\n")
108 .await;
109 let _ = stdout.write_all(b"> ").await;
110 let _ = stdout.flush().await;
111
112 loop {
113 tokio::select! {
114 _ = self.inner.shutdown.notified() => {
115 return Ok(());
116 }
117 line = reader.next_line() => {
118 let line = match line {
119 Ok(Some(l)) => l,
120 Ok(None) => return Ok(()), Err(e) => return Err(ChannelError::SendFailed(e.to_string())),
122 };
123 let trimmed = line.trim();
124 if trimmed.is_empty() {
125 let _ = stdout.write_all(b"> ").await;
126 let _ = stdout.flush().await;
127 continue;
128 }
129 if trimmed.eq_ignore_ascii_case("exit") {
130 return Ok(());
131 }
132
133 let cb_opt = { self.inner.callback.lock().clone() };
137 let cb = match cb_opt {
138 Some(cb) => cb,
139 None => {
140 let _ = stdout.write_all(b"> ").await;
142 let _ = stdout.flush().await;
143 continue;
144 }
145 };
146
147 let chat_id = self.ensure_chat_id();
148 let msg = ChannelMessage {
149 channel_name: CMD_CHANNEL_NAME,
150 chat_connection: ChatConnection {
151 id: chat_id,
152 chat_type: ChatType::Private,
153 channel_name: CMD_CHANNEL_NAME.into(),
154 },
155 message: ChatMessage::text(trimmed.to_string()),
156 reply: build_reply(),
157 inject_instances: Vec::new(),
158 };
159
160 cb(msg).await;
161 let _ = stdout.write_all(b"> ").await;
162 let _ = stdout.flush().await;
163 }
164 }
165 }
166 }
167
168 async fn disconnect(&self) -> Result<(), ChannelError> {
169 *self.inner.callback.lock() = None;
170 self.inner.shutdown.notify_waiters();
171 Ok(())
172 }
173}
174
175fn build_reply() -> wabot_feature_chat_controller::ReplyFn {
176 Box::new(move |msg: ChatMessage| {
177 Box::pin(async move {
178 let mut stdout = tokio::io::stdout();
179 let sender = msg.sender_name.unwrap_or_else(|| "bot".into());
180 let body = msg.text.unwrap_or_default();
181 let _ = stdout
182 .write_all(format!("\n[{sender}]: {body}\n").as_bytes())
183 .await;
184 let _ = stdout.flush().await;
185 Ok::<(), ChannelError>(())
186 }) as std::pin::Pin<Box<dyn std::future::Future<Output = ReplyResult> + Send>>
187 })
188}
189
190impl wabot_core::injection::IsSingleton for CmdChannel {
193 fn register_in(c: &wabot_core::injection::Container) {
194 c.register_singleton_factory::<CmdChannel, _>(|_| Arc::new(CmdChannel::new()));
195 }
196}