kovi_plugin_picture_store/
lib.rs1mod config;
2mod consts;
3
4use std::{
5 path::{Path, PathBuf},
6 sync::{Arc, OnceLock},
7};
8
9use anyhow::{Context, Result, anyhow};
10use bytes::Bytes;
11use consts::*;
12use kovi::{
13 Message, PluginBuilder as plugin, RuntimeBot, Segment,
14 bot::runtimebot::kovi_api::SetAccessControlList,
15 event::id::ID,
16 log::{error, info},
17 serde_json::json,
18 tokio::{
19 fs::{self, File},
20 io::AsyncWriteExt,
21 sync::RwLock,
22 },
23};
24use kovi_onebot::*;
25use reqwest::Client;
26use tinyrand::{Rand, StdRand, Wyrand};
27
28static RAND: OnceLock<RwLock<Wyrand>> = OnceLock::new();
29
30#[kovi::plugin]
31async fn main() {
32 let _ = RAND.set(RwLock::new(StdRand::default()));
33
34 let bot = plugin::get_runtime_bot();
35 let client = Arc::new(reqwest::ClientBuilder::new().build().unwrap());
36
37 let config = config::init(&bot)
38 .await
39 .with_context(|| format!("[{PLUGIN_HEAD}] Error when parsing config"))
40 .unwrap();
41
42 if let Some(groups) = &config.allow_groups {
43 bot.set_plugin_access_control(PLUGIN_NAME, true).unwrap();
44 bot.set_plugin_access_control_list(
45 PLUGIN_NAME,
46 true,
47 SetAccessControlList::Adds(groups.iter().map(|p| p.0.clone()).collect()),
48 )
49 .unwrap();
50 } else {
51 bot.set_plugin_access_control(PLUGIN_NAME, false).unwrap();
52 }
53
54 plugin::on_group_msg({
55 let bot = bot.clone();
56 let client = client.clone();
57 move |msg| on_group_msg(msg, bot.clone(), client.clone())
58 });
59
60 info!("[{PLUGIN_HEAD}] Ready to be a cyber hamster!");
61}
62
63async fn on_group_msg(event: Arc<GroupMsgEvent>, bot: Arc<RuntimeBot>, client: Arc<Client>) {
64 if let Err(err) = handle(event.clone(), bot.clone(), client).await {
65 error!("[{PLUGIN_HEAD}] Error when handling message: \n{err}");
66
67 let cfg = config::CONFIG.get().unwrap();
68
69 if let Some(msg) = &cfg.err_msg {
70 bot.send_group_msg(event.group_id, msg);
71 }
72 }
73}
74
75async fn handle(
76 event: Arc<GroupMsgEvent>,
77 bot: Arc<RuntimeBot>,
78 client: Arc<Client>,
79) -> Result<()> {
80 let cfg = config::CONFIG.get().unwrap();
81
82 let mut is_at = false;
83 let mut reply_id = None;
84 let mut is_send = false;
85 let mut is_store = false;
86 let mut target = None;
87
88 for msg in event.message.clone() {
89 match msg.kind.as_str() {
90 "at" => {
91 let who = msg
92 .data
93 .get("qq")
94 .ok_or(anyhow!("Unable to find 'qq' field in 'at' segment data"))?
95 .as_str()
96 .ok_or(anyhow!(""))?;
97 let who = i64::from_str_radix(who, 10)?;
98 is_at |= who == cfg.self_id.try_as_i64_or_panic();
99 }
100 "reply" => {
101 reply_id = msg
102 .data
103 .get("id")
104 .ok_or(anyhow!("Unable to find 'id' field in 'reply' segment data",))?
105 .as_str()
106 .map_or(None, |i| Some(i.to_string()))
107 }
108 "text" => {
109 let content = msg
110 .data
111 .get("text")
112 .ok_or(anyhow!(
113 "Unable to find 'text' field in 'text' segment data",
114 ))?
115 .as_str()
116 .ok_or(anyhow!("Unable to parse text data from 'text' field"))?
117 .trim();
118 if content.starts_with(cfg.send_trigger.as_str()) {
119 let arg = content[cfg.send_trigger.len()..].to_string();
120 target = if arg.len() > 0 { Some(arg) } else { None };
121 is_send = true
122 }
123 if content.starts_with(cfg.store_trigger.as_str()) {
124 let arg = content[cfg.store_trigger.len()..].to_string();
125 target = if arg.len() > 0 { Some(arg) } else { None };
126 is_store = true
127 }
128 }
129 _ => {}
130 }
131 }
132
133 let group = cfg
134 .allow_groups
135 .as_ref()
136 .and_then(|groups| groups.get(&ID::new(event.group_id)));
137
138 let is_admin = cfg
139 .allow_admins
140 .clone()
141 .is_some_and(|admins| admins.contains(&ID::new(event.user_id)));
142 let has_send_perm = is_admin
143 || group.is_some_and(|group| {
144 group.send.unwrap_or(true)
145 && group
146 .tokens
147 .clone()
148 .is_none_or(|tks| tks.contains(&target.clone().unwrap_or_default()))
149 });
150
151 let has_store_perm = is_admin
152 || group.is_some_and(|group| {
153 group.store.unwrap_or(true)
154 && group
155 .tokens
156 .clone()
157 .is_none_or(|tks| tks.contains(&target.clone().unwrap_or_default()))
158 });
159
160 #[cfg(feature = "taozi")]
161 {
162 let has_taozi_perm = is_admin || group.is_some_and(|group| group.taozi.unwrap_or(true));
163
164 if has_taozi_perm {
165 handle_taozi(event.clone(), bot.clone(), client.clone()).await?;
166 }
167 }
168
169 if !is_at {
170 info!("[{PLUGIN_HEAD}] Not mentioned, don't care");
171 return Ok(());
172 }
173
174 if is_send && is_store {
175 info!("[{PLUGIN_HEAD}] Send & Store in one message, send confused reply");
176 bot.send_group_msg(event.group_id, cfg.cmd_err_msg.clone());
177 return Ok(());
178 }
179
180 if is_store && !has_store_perm {
181 info!(
182 "[{PLUGIN_HEAD}] User {} is not allowed to store",
183 event.user_id
184 );
185 bot.send_group_msg(event.group_id, cfg.no_perm_msg.clone());
186 return Ok(());
187 }
188
189 if is_send && !has_send_perm {
190 info!(
191 "[{PLUGIN_HEAD}] User {} is not allowed to send",
192 event.user_id
193 );
194 bot.send_group_msg(event.group_id, cfg.no_perm_msg.clone());
195 return Ok(());
196 }
197
198 if is_store && reply_id.is_none() {
199 info!("[{PLUGIN_HEAD}] Store without reply");
200 bot.send_group_msg(event.group_id, cfg.no_source_msg.clone());
201 return Ok(());
202 }
203
204 if (is_send || is_store) && target.is_none() {
205 info!("[{PLUGIN_HEAD}] Send / Store with no target provided");
206 bot.send_group_msg(event.group_id, cfg.no_target_msg.clone());
207 return Ok(());
208 }
209
210 let target = target.clone().unwrap().trim().to_string();
211 let target = if target.len() > 128 {
212 target[..128].to_string()
213 } else {
214 target
215 };
216
217 let folder = target
218 .as_bytes()
219 .iter()
220 .map(|c| c.to_string())
221 .collect::<Vec<String>>()
222 .join("");
223
224 info!("[{PLUGIN_HEAD}] Query '{target}' -> '{folder}'");
225 let folder = bot.get_data_path().join("pictures").join(&folder);
226
227 if is_send {
228 if !folder.exists() {
229 info!("[{PLUGIN_HEAD}] Directory does not exist, sending fallback message");
230 bot.send_group_msg(event.group_id, cfg.no_pic_msg.clone());
231 return Ok(());
232 }
233
234 let mut results = fs::read_dir(&folder).await.context(format!(
235 "Unable to read directory {}",
236 folder.to_string_lossy()
237 ))?;
238
239 let mut files: Vec<PathBuf> = vec![];
240
241 info!("[{PLUGIN_HEAD}] Collecting available pictures for '{target}'");
242 loop {
243 let entry = results.next_entry().await.context(format!(
244 "Unable to read directory '{}'",
245 folder.to_string_lossy()
246 ))?;
247
248 if let None = entry {
249 break;
250 }
251
252 let entry = entry.unwrap();
253 files.push(entry.path());
254 }
255
256 if files.is_empty() {
257 info!("[{PLUGIN_HEAD}] No picture found, sending fallback message");
258 bot.send_group_msg(event.group_id, cfg.no_pic_msg.clone());
259 return Ok(());
260 }
261
262 let idx = RAND.get().unwrap().write().await.next_usize() % files.len();
263 let file = &files[idx];
264
265 bot.send_group_msg(
266 event.group_id,
267 Message::from_value(json!(
268 [
269 {
270 "type": "image",
271 "data": {
272 "file": file
273 }
274 }
275 ]
276 ))
277 .context("Error when constructing message")?,
278 );
279 info!("[{PLUGIN_HEAD}] Picture '{}' sent", file.to_string_lossy());
280 } else if is_store {
281 if !folder.exists() {
282 fs::create_dir_all(&folder).await?;
283 }
284
285 let reply_id = reply_id.clone().unwrap();
286 let reply_id = i32::from_str_radix(&reply_id.as_str(), 10)
287 .context(format!("Unable to convert message id '{reply_id}' to i32"))?;
288
289 let source = bot
290 .get_msg(reply_id)
291 .await
292 .map_err(|_| anyhow!("Failed to get message from onebot response"))?;
293 let source = Message::from_value(
294 source
295 .data
296 .get("message")
297 .ok_or(anyhow!("Unable to get 'message' from onebot response"))?
298 .clone(),
299 )
300 .context("Unable to parse valid message object from onebot response")?;
301 if !source.contains("image") {
302 info!("[{PLUGIN_HEAD}] Store without images in reply");
303 bot.send_group_msg(event.group_id, cfg.no_source_msg.clone());
304 return Ok(());
305 }
306
307 for seg in source {
308 if seg.kind != "image" {
309 continue;
310 }
311
312 if let Err(e) = handle_pictures(seg, &folder, client.clone()).await {
313 error!("[{PLUGIN_HEAD}] Error when downloading picture: {e}, Skipping");
314 }
315 }
316
317 bot.send_group_msg(event.group_id, cfg.success_msg.clone());
318 }
319
320 Ok(())
321}
322
323async fn handle_pictures(seg: Segment, folder: &PathBuf, client: Arc<Client>) -> Result<()> {
324 let bytes = handle_image_segment(seg, client).await?;
325 picture_store(bytes, folder).await?;
326 Ok(())
327}
328
329async fn handle_image_segment(seg: Segment, client: Arc<Client>) -> Result<Bytes> {
330 let url = seg
331 .data
332 .get("url")
333 .ok_or(anyhow!("Unable to get 'url' in 'image' segement data"))?
334 .as_str()
335 .ok_or(anyhow!("Unable to parse 'url' as str"))?
336 .to_string();
337
338 let resp = client.get(&url).send().await?;
339 if !resp.status().is_success() {
340 return Err(anyhow!("Unable to download picture '{url}', skipping"));
341 }
342
343 let bytes = resp.bytes().await.context("Failed to read response body")?;
344 Ok(bytes)
345}
346
347async fn picture_store(bytes: bytes::Bytes, folder: &PathBuf) -> Result<()> {
348 let typ = infer::get(&bytes).context("Could not determine file type")?;
349 let checksum = md5::compute(&bytes);
350
351 let name = format!("{:x}.{}", checksum, typ.extension());
352 let path = folder.join(Path::new(&name));
353 let mut file = File::create(&path).await.context(format!(
354 "Failed to create output file {}",
355 path.to_string_lossy()
356 ))?;
357 file.write_all(&bytes)
358 .await
359 .context("Failed to write file")?;
360
361 info!("[{PLUGIN_HEAD}] Picture '{name}' saved");
362 Ok(())
363}
364
365#[cfg(feature = "taozi")]
366async fn handle_taozi(
367 event: Arc<GroupMsgEvent>,
368 bot: Arc<RuntimeBot>,
369 client: Arc<Client>,
370) -> Result<()> {
371 let cfg = config::CONFIG.get().unwrap();
372
373 let msg = event.message.clone();
374 if !msg.contains("image") {
375 info!("[{PLUGIN_HEAD}] Not a img message, ignored");
376 return Ok(());
377 }
378
379 let imgs = msg.get("image");
380 let mut sent = false;
381 for seg in imgs {
382 use ispeach::is_peach;
383
384 let bytes = handle_image_segment(seg, client.clone()).await?;
385 let img = image::load_from_memory(bytes.as_ref())?;
386
387 if !is_peach(&img)? {
388 continue;
389 }
390
391 if !sent {
392 info!("[{PLUGIN_HEAD}] Taozi detected!");
393 bot.send_group_msg(event.group_id, cfg.taozi_msg.clone());
394 sent = true;
395 }
396
397 let folder = bot
398 .get_data_path()
399 .join("pictures")
400 .join("230161131229173144");
401 picture_store(bytes, &folder).await?
402 }
403
404 if !sent {
405 info!("[{PLUGIN_HEAD}] No Taozi detected");
406 }
407
408 Ok(())
409}