Code cleanup

Moved migrations/ into entity/
MessageIds now return errors except for API ones
This commit is contained in:
StNicolay 2024-02-03 16:21:16 +03:00
parent 64e3210cc5
commit bd10acb438
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D
13 changed files with 67 additions and 62 deletions

50
Cargo.lock generated
View File

@ -844,9 +844,9 @@ dependencies = [
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.1.0" version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" checksum = "824b2ae422412366ba479e8111fd301f7b5faece8149317bb81925979a53f520"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown", "hashbrown",
@ -889,9 +889,9 @@ dependencies = [
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.12.0" version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25db6b064527c5d482d0423354fcd07a89a2dfe07b67892e62411946db7f07b0" checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
dependencies = [ dependencies = [
"either", "either",
] ]
@ -922,9 +922,9 @@ dependencies = [
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.152" version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]] [[package]]
name = "libm" name = "libm"
@ -1165,14 +1165,13 @@ dependencies = [
"entity", "entity",
"futures", "futures",
"hex", "hex",
"itertools 0.12.0", "itertools 0.12.1",
"log", "log",
"parking_lot", "parking_lot",
"pretty_env_logger", "pretty_env_logger",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"sqlx",
"teloxide", "teloxide",
"thiserror", "thiserror",
"tokio", "tokio",
@ -1428,9 +1427,9 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.11.23" version = "0.11.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b1ae8d9ac08420c66222fb9096fc5de435c3c48542bc5336c51892cffafb41" checksum = "c6920094eb85afde5e4a138be3f2de8bbdf28000f0029e72c45025a56b042251"
dependencies = [ dependencies = [
"base64", "base64",
"bytes", "bytes",
@ -1455,6 +1454,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sync_wrapper",
"system-configuration", "system-configuration",
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
@ -1520,9 +1520,9 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.30" version = "0.38.31"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca" checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949"
dependencies = [ dependencies = [
"bitflags 2.4.2", "bitflags 2.4.2",
"errno", "errno",
@ -1633,9 +1633,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.112" version = "1.0.113"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d1bd37ce2324cf3bf85e5a25f96eb4baf0d5aa6eba43e7ae8958870c4ec48ed" checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@ -1763,7 +1763,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce81b7bd7c4493975347ef60d8c7e8b742d4694f4c49f93e0a12ea263938176c" checksum = "ce81b7bd7c4493975347ef60d8c7e8b742d4694f4c49f93e0a12ea263938176c"
dependencies = [ dependencies = [
"itertools 0.12.0", "itertools 0.12.1",
"nom", "nom",
"unicode_categories", "unicode_categories",
] ]
@ -1856,7 +1856,6 @@ dependencies = [
"sha2", "sha2",
"sqlx-core", "sqlx-core",
"sqlx-mysql", "sqlx-mysql",
"sqlx-sqlite",
"syn 1.0.109", "syn 1.0.109",
"tempfile", "tempfile",
"tokio", "tokio",
@ -1960,7 +1959,6 @@ dependencies = [
"libsqlite3-sys", "libsqlite3-sys",
"log", "log",
"percent-encoding", "percent-encoding",
"serde",
"sqlx-core", "sqlx-core",
"tracing", "tracing",
"url", "url",
@ -2012,6 +2010,12 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "sync_wrapper"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
[[package]] [[package]]
name = "system-configuration" name = "system-configuration"
version = "0.5.1" version = "0.5.1"
@ -2174,9 +2178,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.35.1" version = "1.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"bytes", "bytes",
@ -2478,9 +2482,9 @@ checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b"
[[package]] [[package]]
name = "wasm-streams" name = "wasm-streams"
version = "0.3.0" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7" checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129"
dependencies = [ dependencies = [
"futures-util", "futures-util",
"js-sys", "js-sys",
@ -2501,9 +2505,9 @@ dependencies = [
[[package]] [[package]]
name = "webpki-roots" name = "webpki-roots"
version = "0.25.3" version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1778a42e8b3b90bff8d0f5032bf22250792889a5cdc752aa0020c84abe3aaf10" checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1"
[[package]] [[package]]
name = "whoami" name = "whoami"

View File

@ -35,15 +35,9 @@ itertools = "0.12"
log = "0.4" log = "0.4"
parking_lot = "0.12" parking_lot = "0.12"
pretty_env_logger = "0.5" pretty_env_logger = "0.5"
serde = "1" serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
sha2 = "0.10" sha2 = "0.10"
sqlx = { version = "0.7", features = [
"mysql",
"runtime-tokio-rustls",
"macros",
"migrate",
], default-features = false }
teloxide = { version = "0.12", features = [ teloxide = { version = "0.12", features = [
"macros", "macros",
"ctrlc_handler", "ctrlc_handler",

View File

@ -10,4 +10,9 @@ workspace = true
[dependencies] [dependencies]
futures = "0.3" futures = "0.3"
sqlx = "0.7" sqlx = { version = "0.7", features = [
"mysql",
"runtime-tokio-rustls",
"macros",
"migrate",
], default-features = false }

View File

@ -2,4 +2,4 @@
fn main() { fn main() {
// trigger recompilation when a new migration is added // trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations"); println!("cargo:rerun-if-changed=migrations");
} }

View File

@ -5,6 +5,8 @@ pub mod account;
pub mod master_pass; pub mod master_pass;
pub mod prelude; pub mod prelude;
pub use sqlx::Result; pub use sqlx::{mysql::MySqlPool as Pool, Result};
pub type Pool = sqlx::mysql::MySqlPool; pub async fn migrate(pool: &Pool) -> Result<(), sqlx::migrate::MigrateError> {
sqlx::migrate!().run(pool).await
}

View File

@ -1,2 +1 @@
pub use crate::account::Account; pub use crate::{account::Account, master_pass::MasterPass, Pool};
pub use crate::master_pass::MasterPass;

View File

@ -29,7 +29,7 @@ async fn get_master_pass(
) -> crate::Result<()> { ) -> crate::Result<()> {
dialogue.exit().await?; dialogue.exit().await?;
ids.delete(&bot).await; ids.delete(&bot).await?;
let user_id = msg.from().ok_or(NoUserInfo)?.id.0; let user_id = msg.from().ok_or(NoUserInfo)?.id.0;
let mut accounts = Vec::new(); let mut accounts = Vec::new();

View File

@ -36,7 +36,7 @@ macro_rules! handler {
async fn $function_name( async fn $function_name(
bot: Throttle<Bot>, bot: Throttle<Bot>,
_: Message, _: Message,
_: DatabaseConnection, _: Pool,
dialogue: MainDialogue, dialogue: MainDialogue,
mut ids: MessageIds, mut ids: MessageIds,
$($param: $type),* $($param: $type),*
@ -57,7 +57,7 @@ macro_rules! simple_state_handler {
pub async fn $function_name( pub async fn $function_name(
bot: Throttle<Bot>, bot: Throttle<Bot>,
msg: Message, msg: Message,
db: DatabaseConnection, db: Pool,
dialogue: MainDialogue, dialogue: MainDialogue,
next: PackagedHandler<String>, next: PackagedHandler<String>,
) -> $crate::Result<()> { ) -> $crate::Result<()> {

View File

@ -87,9 +87,9 @@ async fn main() -> Result<()> {
let token = env::var("TOKEN").expect("expected TOKEN in the enviroment"); let token = env::var("TOKEN").expect("expected TOKEN in the enviroment");
let database_url = env::var("DATABASE_URL").expect("expected DATABASE_URL in the enviroment"); let database_url = env::var("DATABASE_URL").expect("expected DATABASE_URL in the enviroment");
let pool = sqlx::mysql::MySqlPool::connect(&database_url).await?; let pool = DatabaseConnection::connect(&database_url).await?;
sqlx::migrate!().run(&pool).await?; entity::migrate(&pool).await?;
get_dispatcher(token, pool).dispatch().await; get_dispatcher(token, pool).dispatch().await;
Ok(()) Ok(())

View File

@ -1,4 +1,5 @@
use crate::prelude::*; use crate::prelude::*;
use futures::TryFutureExt;
use itertools::Itertools; use itertools::Itertools;
use std::{fmt::Write, path::Path}; use std::{fmt::Write, path::Path};
use teloxide::{ use teloxide::{
@ -35,7 +36,7 @@ async fn download_file(bot: &Throttle<Bot>, file: &FileMeta) -> crate::Result<Ve
let mut data = Vec::with_capacity(file.size as usize); let mut data = Vec::with_capacity(file.size as usize);
bot.download_file_stream(&path) bot.download_file_stream(&path)
.try_for_each(|bytes| { .try_for_each(|bytes| {
data.extend(bytes); data.extend_from_slice(&bytes);
async { Ok(()) } async { Ok(()) }
}) })
.await?; .await?;
@ -163,12 +164,9 @@ pub async fn get_user(
} }
}; };
let existing_names = async { let existing_names = Account::get_names(user_id, &db)
Account::get_names(user_id, &db) .try_collect()
.try_collect() .map_err(Into::into);
.await
.map_err(Into::into)
};
let (data, existing_names) = try_join!(download_file(&bot, file), existing_names)?; let (data, existing_names) = try_join!(download_file(&bot, file), existing_names)?;

View File

@ -1,27 +1,27 @@
use crate::prelude::*; use crate::prelude::*;
use futures::future::BoxFuture; use futures::{future::BoxFuture, TryFutureExt};
use std::{mem, sync::Arc}; use std::{mem, sync::Arc};
use teloxide::{ use teloxide::{
requests::HasPayload, requests::HasPayload,
types::{InlineKeyboardMarkup, MessageId, ParseMode}, types::{InlineKeyboardMarkup, MessageId, ParseMode},
RequestError, RequestError,
}; };
use tokio::{join, sync::Mutex}; use tokio::{sync::Mutex, try_join};
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct MessageIds(pub ChatId, pub MessageId); pub struct MessageIds(pub ChatId, pub MessageId);
impl MessageIds { impl MessageIds {
// Tries to delete the message while ignoring API errors
#[inline] #[inline]
pub async fn delete(self, bot: &Throttle<Bot>) { pub async fn delete(self, bot: &Throttle<Bot>) -> crate::Result<()> {
let _ = bot.delete_message(self.0, self.1).await; match bot.delete_message(self.0, self.1).await {
Ok(_) | Err(RequestError::Api(_)) => Ok(()),
Err(err) => Err(err.into()),
}
} }
/// Tries to alter the message or sends a new one /// Tries to alter the message or sends a new one
///
/// # Returns
///
/// Returns true if the message was edited successfully. Returns false otherwise
#[inline] #[inline]
pub async fn alter_message( pub async fn alter_message(
&mut self, &mut self,
@ -40,12 +40,15 @@ impl MessageIds {
Err(err) => return Err(err.into()), Err(err) => return Err(err.into()),
}; };
let mut send = bot.send_message(self.0, mem::take(&mut edit.text)); let send = {
let payload = send.payload_mut(); let mut send_request = bot.send_message(self.0, mem::take(&mut edit.text));
payload.parse_mode = edit.parse_mode; let payload = send_request.payload_mut();
payload.reply_markup = mem::take(&mut edit.reply_markup).map(Into::into); payload.parse_mode = edit.parse_mode;
payload.reply_markup = edit.reply_markup.take().map(Into::into);
send_request.send().map_err(Into::into)
};
let msg = join!(self.delete(bot), send.send()).1?; let msg = try_join!(self.delete(bot), send)?.1;
*self = Self::from(&msg); *self = Self::from(&msg);
Ok(()) Ok(())
} }
@ -70,7 +73,7 @@ type DynHanlder<T> = Box<
+ Send, + Send,
>; >;
pub struct Handler<T: ?Sized> { pub struct Handler<T> {
pub func: Option<DynHanlder<T>>, pub func: Option<DynHanlder<T>>,
pub previous: MessageIds, pub previous: MessageIds,