add deltachat login and command handler stubs

This commit is contained in:
2026-03-20 19:28:07 +03:00
parent 63209cefc2
commit 87b4fd3087
4 changed files with 358 additions and 6 deletions

136
src/handler.rs Normal file
View File

@@ -0,0 +1,136 @@
use std::{collections::HashSet, sync::Arc};
use anyhow::Result as AnyhowResult;
use deltachat::{
chat::{self, ChatId},
contact::ContactId,
context::Context,
message::Message,
};
use tokio::sync::Mutex;
use crate::config::BotConfig;
pub struct BotContext {
authed_contacts: HashSet<ContactId>,
config: BotConfig,
}
impl BotContext {
pub fn new(config: BotConfig) -> BotContext {
BotContext {
authed_contacts: HashSet::new(),
config,
}
}
}
pub async fn echo(dchat_ctx: Arc<Mutex<Context>>, msg: Message) -> AnyhowResult<()> {
let chat_id = msg.get_chat_id();
let dchat_ctx_lock = dchat_ctx.lock().await;
chat::send_text_msg(&dchat_ctx_lock, chat_id, msg.get_text()).await?;
Ok(())
}
pub async fn auth_command(
dchat_ctx: Arc<Mutex<Context>>,
ctx: Arc<Mutex<BotContext>>,
msg: Message,
args: &[&str],
) -> AnyhowResult<()> {
let chat_id = msg.get_chat_id();
let contact_id = msg.get_from_id();
let mut ctx_lock = ctx.lock().await;
let dchat_ctx_lock = dchat_ctx.lock().await;
if ctx_lock.authed_contacts.contains(&contact_id) {
chat::send_text_msg(&dchat_ctx_lock, chat_id, "Already authenticated".to_owned()).await?;
return Ok(());
}
let Some(password) = args.first() else {
chat::send_text_msg(
&dchat_ctx_lock,
chat_id,
"Usage: /auth <password>".to_owned(),
)
.await?;
return Ok(());
};
if *password == ctx_lock.config.auth.password {
ctx_lock.authed_contacts.insert(contact_id);
chat::send_text_msg(
&dchat_ctx_lock,
chat_id,
"Authentication successful!".to_owned(),
)
.await?;
} else {
chat::send_text_msg(&dchat_ctx_lock, chat_id, "Incorrect password".to_owned()).await?;
}
Ok(())
}
pub async fn wol_command(
dchat_ctx: Arc<Mutex<Context>>,
ctx: Arc<Mutex<BotContext>>,
msg: Message,
args: &[&str],
) -> AnyhowResult<()> {
let chat_id = msg.get_chat_id();
let contact_id = msg.get_from_id();
let ctx_lock = ctx.lock().await;
let dchat_ctx_lock = dchat_ctx.lock().await;
if !ensure_auth(&dchat_ctx_lock, &ctx_lock, chat_id, contact_id).await? {
return Ok(());
}
// TODO
Ok(())
}
pub async fn ssh_unlock_disk_command(
dchat_ctx: Arc<Mutex<Context>>,
ctx: Arc<Mutex<BotContext>>,
msg: Message,
args: &[&str],
) -> AnyhowResult<()> {
let chat_id = msg.get_chat_id();
let contact_id = msg.get_from_id();
let ctx_lock = ctx.lock().await;
let dchat_ctx_lock = dchat_ctx.lock().await;
if !ensure_auth(&dchat_ctx_lock, &ctx_lock, chat_id, contact_id).await? {
return Ok(());
}
// TODO
Ok(())
}
async fn ensure_auth(
dchat_ctx: &Context,
ctx: &BotContext,
chat_id: ChatId,
contact_id: ContactId,
) -> AnyhowResult<bool> {
if !ctx.authed_contacts.contains(&contact_id) {
chat::send_text_msg(
dchat_ctx,
chat_id,
"Authenticate yourself first with '/auth <password>'.".to_owned(),
)
.await?;
Ok(false)
} else {
Ok(true)
}
}