89 lines
2.6 KiB
Rust
89 lines
2.6 KiB
Rust
|
use crate::{
|
||
|
errors::HandlerUsed,
|
||
|
handlers::{markups::deletion_markup, utils::delete_optional, MainDialogue},
|
||
|
models::User,
|
||
|
};
|
||
|
use futures::TryStreamExt;
|
||
|
use sea_orm::prelude::*;
|
||
|
use teloxide::{adaptors::Throttle, net::Download, prelude::*};
|
||
|
use tokio::task::spawn_blocking;
|
||
|
|
||
|
/// Function to handle GetUser state. It doesn't actually validate anything
|
||
|
pub async fn get_user(
|
||
|
bot: Throttle<Bot>,
|
||
|
msg: Message,
|
||
|
db: DatabaseConnection,
|
||
|
dialogue: MainDialogue,
|
||
|
next: super::PackagedHandler<User>,
|
||
|
) -> crate::Result<()> {
|
||
|
let mut handler = next.lock().await;
|
||
|
delete_optional(&bot, handler.previous.as_ref()).await;
|
||
|
|
||
|
if let Some("/cancel") = msg.text().map(str::trim_end) {
|
||
|
dialogue.exit().await?;
|
||
|
bot.send_message(msg.chat.id, "Successfully cancelled")
|
||
|
.reply_markup(deletion_markup())
|
||
|
.await?;
|
||
|
return Ok(());
|
||
|
}
|
||
|
|
||
|
if handler.func.is_none() {
|
||
|
let _ = dialogue.exit().await;
|
||
|
return Err(HandlerUsed.into());
|
||
|
}
|
||
|
|
||
|
let document = match msg.document() {
|
||
|
Some(document) => document,
|
||
|
None => {
|
||
|
let msg = bot
|
||
|
.send_message(msg.chat.id, "You didn't send a file. Try again")
|
||
|
.await?;
|
||
|
handler.previous = Some(msg);
|
||
|
return Ok(());
|
||
|
}
|
||
|
};
|
||
|
|
||
|
match document.file_name.as_deref() {
|
||
|
Some(name) if name.trim_end().ends_with(".json") => (),
|
||
|
_ => {
|
||
|
let msg = bot
|
||
|
.send_message(
|
||
|
msg.chat.id,
|
||
|
"Invalid file name. You need to send a json file. Try again",
|
||
|
)
|
||
|
.await?;
|
||
|
handler.previous = Some(msg);
|
||
|
return Ok(());
|
||
|
}
|
||
|
}
|
||
|
|
||
|
let file = bot.get_file(&document.file.id).await?;
|
||
|
let mut data = Vec::with_capacity(document.file.size as usize);
|
||
|
bot.download_file_stream(&file.path)
|
||
|
.try_for_each(|bytes| {
|
||
|
data.extend(bytes);
|
||
|
async { Ok(()) }
|
||
|
})
|
||
|
.await?;
|
||
|
|
||
|
let user: User = match spawn_blocking(move || serde_json::from_slice(&data)).await? {
|
||
|
Ok(user) => user,
|
||
|
Err(_) => {
|
||
|
let msg = bot
|
||
|
.send_message(msg.chat.id, "Error parsing the json file. Try again")
|
||
|
.await?;
|
||
|
handler.previous = Some(msg);
|
||
|
return Ok(());
|
||
|
}
|
||
|
};
|
||
|
|
||
|
let func = handler.func.take().unwrap();
|
||
|
drop(handler);
|
||
|
|
||
|
if let Err(err) = func(bot, msg, db, dialogue.clone(), user).await {
|
||
|
let _ = dialogue.exit().await;
|
||
|
return Err(err);
|
||
|
}
|
||
|
Ok(())
|
||
|
}
|