reminder-bot/src/models/user_data.rs

119 lines
2.8 KiB
Rust
Raw Normal View History

use chrono_tz::Tz;
use log::error;
2022-02-19 14:32:03 +00:00
use poise::serenity::{http::CacheHttp, model::id::UserId};
2021-07-16 20:28:51 +00:00
use sqlx::MySqlPool;
use crate::consts::LOCAL_TIMEZONE;
2021-07-16 20:28:51 +00:00
pub struct UserData {
pub id: u32,
pub user: u64,
pub dm_channel: u32,
pub timezone: String,
}
impl UserData {
pub async fn timezone_of<U>(user: U, pool: &MySqlPool) -> Tz
where
U: Into<UserId>,
{
let user_id = user.into().as_u64().to_owned();
match sqlx::query!(
"
SELECT timezone FROM users WHERE user = ?
",
user_id
)
.fetch_one(pool)
.await
{
Ok(r) => r.timezone,
Err(_) => LOCAL_TIMEZONE.clone(),
}
.parse()
.unwrap()
}
2022-02-19 14:32:03 +00:00
pub async fn from_user<U: Into<UserId>>(
user: U,
2021-07-16 20:28:51 +00:00
ctx: impl CacheHttp,
pool: &MySqlPool,
) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
2022-02-19 14:32:03 +00:00
let user_id = user.into();
2021-07-16 20:28:51 +00:00
match sqlx::query_as_unchecked!(
Self,
"
2022-02-19 14:32:03 +00:00
SELECT id, user, dm_channel, IF(timezone IS NULL, ?, timezone) AS timezone FROM users WHERE user = ?
2021-07-16 20:28:51 +00:00
",
*LOCAL_TIMEZONE,
2022-02-19 14:32:03 +00:00
user_id.0
2021-07-16 20:28:51 +00:00
)
.fetch_one(pool)
.await
{
Ok(c) => Ok(c),
Err(sqlx::Error::RowNotFound) => {
2022-02-19 14:32:03 +00:00
let dm_channel = user_id.create_dm_channel(ctx).await?;
2021-07-16 20:28:51 +00:00
let pool_c = pool.clone();
sqlx::query!(
"
INSERT IGNORE INTO channels (channel) VALUES (?)
",
2022-02-19 14:32:03 +00:00
dm_channel.id.0
2021-07-16 20:28:51 +00:00
)
.execute(&pool_c)
.await?;
sqlx::query!(
"
INSERT INTO users (name, user, dm_channel, timezone) VALUES ('', ?, (SELECT id FROM channels WHERE channel = ?), ?)
",
2022-02-19 14:32:03 +00:00
user_id.0,
dm_channel.id.0,
*LOCAL_TIMEZONE
)
.execute(&pool_c)
.await?;
2021-07-16 20:28:51 +00:00
Ok(sqlx::query_as_unchecked!(
Self,
"
2022-02-19 14:32:03 +00:00
SELECT id, user, dm_channel, timezone FROM users WHERE user = ?
2021-07-16 20:28:51 +00:00
",
2022-02-19 14:32:03 +00:00
user_id.0
2021-07-16 20:28:51 +00:00
)
.fetch_one(pool)
.await?)
}
Err(e) => {
error!("Error querying for user: {:?}", e);
Err(Box::new(e))
}
2021-07-16 20:28:51 +00:00
}
}
pub async fn commit_changes(&self, pool: &MySqlPool) {
sqlx::query!(
"
2022-02-19 14:32:03 +00:00
UPDATE users SET timezone = ? WHERE id = ?
2021-07-16 20:28:51 +00:00
",
self.timezone,
self.id
)
.execute(pool)
.await
.unwrap();
}
pub fn timezone(&self) -> Tz {
self.timezone.parse().unwrap()
}
}