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

View File

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

View File

@ -10,4 +10,9 @@ workspace = true
[dependencies]
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() {
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed=migrations");
}
}

View File

@ -5,6 +5,8 @@ pub mod account;
pub mod master_pass;
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::master_pass::MasterPass;
pub use crate::{account::Account, master_pass::MasterPass, Pool};

View File

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

View File

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

View File

@ -87,9 +87,9 @@ async fn main() -> Result<()> {
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 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;
Ok(())

View File

@ -1,4 +1,5 @@
use crate::prelude::*;
use futures::TryFutureExt;
use itertools::Itertools;
use std::{fmt::Write, path::Path};
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);
bot.download_file_stream(&path)
.try_for_each(|bytes| {
data.extend(bytes);
data.extend_from_slice(&bytes);
async { Ok(()) }
})
.await?;
@ -163,12 +164,9 @@ pub async fn get_user(
}
};
let existing_names = async {
Account::get_names(user_id, &db)
.try_collect()
.await
.map_err(Into::into)
};
let existing_names = Account::get_names(user_id, &db)
.try_collect()
.map_err(Into::into);
let (data, existing_names) = try_join!(download_file(&bot, file), existing_names)?;

View File

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