add: model

This commit is contained in:
trisua 2025-08-23 22:07:14 -04:00
parent f70b92c558
commit d7ee379a9a
13 changed files with 394 additions and 219 deletions

View file

@ -2,6 +2,12 @@ use oiseau::config::{Configuration, DatabaseConfig};
use pathbufd::PathBufD;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ServiceHostsConfig {
pub tetratto: String,
pub buckets: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
/// The name of the site. Shown in the UI.
@ -13,17 +19,24 @@ pub struct Config {
/// Real IP header (for reverse proxy).
#[serde(default = "default_real_ip_header")]
pub real_ip_header: String,
/// The host URL of additional services the app needs.
#[serde(default = "default_service_hosts")]
pub service_hosts: ServiceHostsConfig,
/// The location of the uploads directory. Should match `directory` in your
/// buckets config.
#[serde(default = "default_uploads_dir")]
pub uploads_dir: String,
/// Database configuration.
#[serde(default = "default_database")]
pub database: DatabaseConfig,
}
fn default_name() -> String {
"App".to_string()
"Tawny".to_string()
}
fn default_theme_color() -> String {
"#6ee7b7".to_string()
"#cd5700".to_string()
}
fn default_real_ip_header() -> String {
@ -34,6 +47,17 @@ fn default_database() -> DatabaseConfig {
DatabaseConfig::default()
}
fn default_service_hosts() -> ServiceHostsConfig {
ServiceHostsConfig {
tetratto: String::new(),
buckets: String::new(),
}
}
fn default_uploads_dir() -> String {
"./uploads".to_string()
}
impl Configuration for Config {
fn db_config(&self) -> DatabaseConfig {
self.database.to_owned()
@ -46,6 +70,8 @@ impl Default for Config {
name: default_name(),
theme_color: default_theme_color(),
real_ip_header: default_real_ip_header(),
service_hosts: default_service_hosts(),
uploads_dir: default_uploads_dir(),
database: default_database(),
}
}

101
src/database/chats.rs Normal file
View file

@ -0,0 +1,101 @@
use super::DataManager;
use crate::model::{Chat, ChatStyle};
use oiseau::{PostgresRow, cache::Cache, execute, get, params};
use tetratto_core::{
auto_method,
model::{Error, Result},
};
impl DataManager {
/// Get a [`Chat`] from an SQL row.
pub(crate) fn get_chat_from_row(x: &PostgresRow) -> Chat {
Chat {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
style: serde_json::from_str(&get!(x->2(String))).unwrap(),
members: serde_json::from_str(&get!(x->3(String))).unwrap(),
last_message_created: get!(x->4(i64)) as usize,
last_message_read_by: serde_json::from_str(&get!(x->5(String))).unwrap(),
}
}
auto_method!(get_chat_by_id(usize as i64)@get_chat_from_row -> "SELECT * FROM t_chats WHERE id = $1" --name="chat" --returns=Chat --cache-key-tmpl="twny.chat:{}");
/// Create a new chat in the database.
///
/// # Arguments
/// * `data` - a mock [`Chat`] object to insert
pub async fn create_chat(&self, data: Chat) -> Result<Chat> {
// check values
if let ChatStyle::Group(ref info) = data.style {
if info.name.trim().len() < 2 {
return Err(Error::DataTooShort("name".to_string()));
} else if info.name.len() > 128 {
return Err(Error::DataTooLong("name".to_string()));
}
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO t_chats VALUES ($1, $2, $3, $4, $5, $6)",
params![
&(data.id as i64),
&(data.created as i64),
&serde_json::to_string(&data.style).unwrap(),
&serde_json::to_string(&data.members).unwrap(),
&(data.last_message_created as i64),
&serde_json::to_string(&data.last_message_read_by).unwrap()
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
/// Delete an existing chat.
pub async fn delete_chat(&self, id: usize) -> Result<()> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
// delete chat
let res = execute!(
&conn,
"DELETE FROM t_chats WHERE id = $1",
params![&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete messages
let res = execute!(
&conn,
"DELETE FROM t_messages WHERE chat = $1",
params![&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// ...
Ok(())
}
auto_method!(update_chat_style(ChatStyle) -> "UPDATE t_chats SET style = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
auto_method!(update_chat_members(Vec<usize>) -> "UPDATE t_chats SET members = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
auto_method!(update_chat_last_message_read_by(Vec<usize>) -> "UPDATE t_chats SET last_message_read_by = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.chat:{}");
auto_method!(update_chat_last_message_created(i64) -> "UPDATE t_chats SET last_message_created = $1 WHERE id = $2" --cache-key-tmpl="twny.chat:{}");
}

99
src/database/messages.rs Normal file
View file

@ -0,0 +1,99 @@
use super::DataManager;
use crate::model::Message;
use oiseau::{PostgresRow, cache::Cache, execute, get, params};
use tetratto_core::{
auto_method,
model::{Error, Result, auth::User},
};
impl DataManager {
/// Get a [`Message`] from an SQL row.
pub(crate) fn get_message_from_row(x: &PostgresRow) -> Message {
Message {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
chat: get!(x->3(i64)) as usize,
content: get!(x->4(String)),
uploads: serde_json::from_str(&get!(x->5(String))).unwrap(),
}
}
auto_method!(get_message_by_id(usize as i64)@get_message_from_row -> "SELECT * FROM t_messages WHERE id = $1" --name="message" --returns=Message --cache-key-tmpl="twny.message:{}");
/// Create a new message in the database.
///
/// # Arguments
/// * `data` - a mock [`Message`] object to insert
pub async fn create_message(&self, data: Message) -> Result<Message> {
// check values
if data.content.trim().len() < 2 {
return Err(Error::DataTooShort("content".to_string()));
} else if data.content.len() > 2048 {
return Err(Error::DataTooLong("content".to_string()));
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO t_messages VALUES ($1, $2, $3, $4, $5, $6)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&(data.chat as i64),
&data.content,
&serde_json::to_string(&data.uploads).unwrap(),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
/// Delete an existing message.
pub async fn delete_message(&self, id: usize, user: &User) -> Result<()> {
let message = self.get_message_by_id(id).await?;
if message.owner != user.id {
return Err(Error::NotAllowed);
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
// delete message
let res = execute!(
&conn,
"DELETE FROM t_messages WHERE id = $1",
params![&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// delete uploads
for upload in message.uploads {
if let Err(e) = self.1.delete_upload(upload).await {
return Err(Error::MiscError(e.to_string()));
}
}
// ...
Ok(())
}
auto_method!(update_message_content(&str) -> "UPDATE t_messages SET content = $1 WHERE id = $2" --serde --cache-key-tmpl="twny.message:{}");
}

View file

@ -1,18 +1,28 @@
mod chats;
mod messages;
mod sql;
use crate::config::Config;
use buckets_core::{Config as BucketsConfig, DataManager as BucketsManager};
use oiseau::{execute, postgres::DataManager as OiseauManager, postgres::Result as PgResult};
use std::collections::HashMap;
use tetratto_core::model::{Error, Result};
pub const NAME_REGEX: &str = r"[^\w_\-\.,!]+";
#[derive(Clone)]
pub struct DataManager(pub OiseauManager<Config>);
pub struct DataManager(pub OiseauManager<Config>, pub BucketsManager);
impl DataManager {
/// Create a new [`DataManager`].
pub async fn new(config: Config) -> PgResult<Self> {
Ok(Self(OiseauManager::new(config).await?))
let buckets_manager = BucketsManager::new(BucketsConfig {
directory: config.uploads_dir.clone(),
bucket_defaults: HashMap::new(),
database: config.database.clone(),
})
.await
.expect("failed to create buckets manager");
Ok(Self(OiseauManager::new(config).await?, buckets_manager))
}
/// Initialize tables.
@ -22,7 +32,8 @@ impl DataManager {
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
// execute!(&conn, sql::CREATE_TABLE_ENTRIES).unwrap();
execute!(&conn, sql::CREATE_TABLE_CHATS).unwrap();
execute!(&conn, sql::CREATE_TABLE_MESSAGES).unwrap();
Ok(())
}

View file

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS t_chats (
id BIGINT NOT NULL,
created BIGINT NOT NULL,
style TEXT NOT NULL,
members TEXT NOT NULL,
last_message_created BIGINT NOT NULL,
last_message_read_by TEXT NOT NULL
);

View file

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS t_messages (
id BIGINT NOT NULL,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
chats BIGINT NOT NULL,
content TEXT NOT NULL,
uploads TEXT NOT NULL
);

View file

@ -1 +1,2 @@
// pub const CREATE_TABLE_ENTRIES: &str = include_str!("./create_entries.sql");
pub const CREATE_TABLE_CHATS: &str = include_str!("./create_chats.sql");
pub const CREATE_TABLE_MESSAGES: &str = include_str!("./create_messages.sql");

View file

@ -125,7 +125,7 @@ async fn main() {
.await
.unwrap();
info!("🪨 malachite.");
info!("🦉 tawny.");
info!("listening on http://0.0.0.0:{}", port);
axum::serve(
listener,

View file

@ -1 +1,73 @@
//! Base types matching SQL table structures.
use serde::{Deserialize, Serialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
#[derive(Serialize, Deserialize)]
pub struct GroupChatInfo {
pub name: String,
}
#[derive(Serialize, Deserialize)]
pub enum ChatStyle {
/// Direct messages between two users.
Direct,
/// Messages between a group of users (up to 10).
Group(GroupChatInfo),
}
#[derive(Serialize, Deserialize)]
pub struct Chat {
pub id: usize,
pub created: usize,
pub style: ChatStyle,
/// When the last member of the chat leaves, the chat will be deleted.
pub members: Vec<usize>,
pub last_message_created: usize,
/// The IDs of each user in the chat who read the last message.
///
/// Will always have the ID of the user who sent the last message as index 0.
///
/// The UI should show two checkmarks once this vector has a length of at least 2.
///
/// Read receipts are stored by chat instead of message since it's easier to
/// keep up with if we store by chat instead. This will also declutter
/// the UI and prevent every message showing a read receipt.
pub last_message_read_by: Vec<usize>,
}
impl Chat {
/// Create a new [`Chat`].
pub fn new(style: ChatStyle, members: Vec<usize>) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
style,
members,
last_message_created: 0,
last_message_read_by: Vec::new(),
}
}
}
#[derive(Serialize, Deserialize)]
pub struct Message {
pub id: usize,
pub created: usize,
pub owner: usize,
pub chat: usize,
pub content: String,
pub uploads: Vec<usize>,
}
impl Message {
/// Create a new [`Message`].
pub fn new(owner: usize, chat: usize, content: String, uploads: Vec<usize>) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
owner,
chat,
content,
uploads,
}
}
}