Working supabase structure

This commit is contained in:
2025-10-13 12:30:42 +02:00
parent 3911274bc1
commit 721a79cf74
7 changed files with 63 additions and 53 deletions
+3 -3
View File
@@ -9,17 +9,17 @@ logger!(LOGGER "Auth");
#[derive(Debug, Deserialize)]
struct AuthApiRes {
user_id: u32,
user_id: String,
}
pub fn auth(_server: &Arc<Server>, client: &mut Client, token: &str) -> crate::Result<u32> {
pub fn auth(_server: &Arc<Server>, client: &mut Client, token: &str) -> crate::Result<String> {
let mut res = ureq::get(format!(
"http://localhost:3000/api/auth?intents=server&token={token}"
))
.call()
.context("Failed to authenticate")?;
let api_res: AuthApiRes = serde_json::from_str(&res.body_mut().read_to_string()?)?;
client.set_uuid(api_res.user_id);
client.set_uuid(&api_res.user_id);
LOGGER.info(format!("{} successfully authenticated", api_res.user_id));
Ok(api_res.user_id)
}
+5 -2
View File
@@ -7,7 +7,7 @@ crate::logger!(LOGGER "Message Manager");
pub fn send(
server: &Arc<Server>,
client: &Client,
channel_id: u32,
channel_id: &str,
contents: &str,
) -> crate::Result<()> {
LOGGER.info(format!("SendMessage to {channel_id}: {contents}"));
@@ -22,17 +22,19 @@ pub fn send(
let msg = server.db.insert_message(
channel_id,
client.get_uuid()?,
&client.get_uuid()?,
&contents,
chrono::Utc::now().timestamp(),
)?;
if msg.from != msg.channel_id {
let server = server.clone();
for c in server.clients.lock().unwrap().iter() {
let c = c.clone();
let server = server.clone();
let msg = msg.clone();
let channel_id = channel_id.to_string();
std::thread::spawn(move || {
if let Some(uuid) =
@@ -49,6 +51,7 @@ pub fn send(
}
});
}
}
LOGGER.extract(
server.wrap_err(
+1 -1
View File
@@ -21,7 +21,7 @@ impl Server {
channel_id,
contents,
} => {
message::send(self, client, *channel_id, contents)?;
message::send(self, client, channel_id, contents)?;
}
ClientMessage::EditMessage {
+3 -3
View File
@@ -117,11 +117,11 @@ impl Server {
self.wrap_err(
&client,
client.send(types::ServerMessage::Authenticated {
uuid,
uuid: uuid.clone(),
messages: if let Some(i) = last_message {
self.wrap_err(&client, self.db.get_messages_after_id(uuid, i))?
self.wrap_err(&client, self.db.get_messages_after_id(&uuid, i))?
} else {
self.wrap_err(&client, self.db.get_messages_after_id(uuid, 0))?
self.wrap_err(&client, self.db.get_messages_after_id(&uuid, 0))?
},
}),
)?;
+12 -8
View File
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
pub enum ClientMessage {
/// Send a message to a channel
SendMessage {
channel_id: u32,
channel_id: String,
contents: String,
},
@@ -26,7 +26,7 @@ pub enum ClientMessage {
pub enum ServerMessage {
/// Successful authentication
Authenticated {
uuid: u32,
uuid: Author,
messages: Vec<data::Message>,
},
@@ -42,20 +42,20 @@ pub enum ServerMessage {
/// A message was deleted
MessageDelete {
channel_id: u32,
channel_id: String,
message_id: usize,
},
/// Presence updates
PresenceUpdate {
user_id: String,
user_id: Author,
status: String,
},
/// Typing indicator
Typing {
user_id: String,
channel_id: u32,
user_id: Author,
channel_id: String,
},
}
@@ -77,15 +77,19 @@ pub enum WsMessage<T: Serialize + for<'de> Deserialize<'de>> {
String(String),
}
pub type Author = String;
/// Shared data structures
pub mod data {
use serde::{Deserialize, Serialize};
use crate::types::Author;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub id: i64,
pub channel_id: u32,
pub from: u32,
pub channel_id: String,
pub from: Author,
pub contents: String,
pub timestamp: i64,
}
+8 -5
View File
@@ -100,7 +100,7 @@ pub mod handshake {
}
}
pub struct Client(TcpStream, Option<u32>, u64);
pub struct Client(TcpStream, Option<String>, u64);
impl Client {
/// Create a client with no timeouts
@@ -324,12 +324,15 @@ impl Client {
self.read_t()
}
pub fn get_uuid(&self) -> crate::Result<u32> {
self.1.ok_or(anyhow!("Invalid UUID"))
pub fn get_uuid(&self) -> crate::Result<String> {
match &self.1 {
Some(v) => Ok(v.clone()),
None => Err(anyhow!("Client ({}) UUID not set", self.2).into()),
}
}
pub fn set_uuid(&mut self, uuid: u32) {
self.1 = Some(uuid)
pub fn set_uuid(&mut self, uuid: &str) {
self.1 = Some(uuid.to_string())
}
#[deprecated]
+13 -13
View File
@@ -1,4 +1,4 @@
use crate::{server::ServerConfig, types::data::Message};
use crate::{ServerConfig, types::data::Message};
use rusqlite::{Connection, Result, params};
pub struct Database(Connection);
@@ -11,8 +11,8 @@ impl Database {
conn.execute(
"CREATE TABLE IF NOT EXISTS chat (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
channel_id TEXT NOT NULL,
user_id TEXT NOT NULL,
contents TEXT NOT NULL,
timestamp INTEGER NOT NULL
)",
@@ -29,8 +29,8 @@ impl Database {
/// Insert a message into the DB
pub fn insert_message(
&self,
channel_id: u32,
user_id: u32,
channel_id: &str,
user_id: &str,
contents: &str,
timestamp: i64,
) -> Result<Message> {
@@ -44,8 +44,8 @@ impl Database {
Ok(Message {
id,
channel_id,
from: user_id,
channel_id: channel_id.to_string(),
from: user_id.to_string(),
contents: contents.to_string(),
timestamp,
})
@@ -73,7 +73,7 @@ impl Database {
}
/// Get a message by its ID
pub fn get_message_by_id(&self, message_id: usize) -> Result<Option<Message>> {
pub fn get_message_by_id(&self, message_id: &str) -> Result<Option<Message>> {
let mut stmt = self.0.prepare(
"SELECT id, channel_id, user_id, contents, timestamp
FROM chat
@@ -83,7 +83,7 @@ impl Database {
let mut rows = stmt.query_map(params![message_id], |row| {
Ok((
row.get::<_, i64>(0)?, // id
row.get::<_, u32>(1)?, // channel_id
row.get::<_, String>(1)?, // channel_id
row.get::<_, u32>(2)?, // user_id
row.get::<_, String>(3)?, // contents
row.get::<_, i64>(4)?, // timestamp
@@ -95,7 +95,7 @@ impl Database {
return Ok(Some(Message {
id,
channel_id,
from: user_id,
from: user_id.to_string(),
contents,
timestamp,
}));
@@ -106,7 +106,7 @@ impl Database {
/// Get all messages with an ID greater than the given one
pub fn get_messages_after_id(
&self,
channel_id: u32,
channel_id: &str,
message_id: usize,
) -> Result<Vec<Message>> {
let mut stmt = self.0.prepare(
@@ -120,8 +120,8 @@ impl Database {
let rows = stmt.query_map(params![message_id, channel_id], |row| {
Ok(Message {
id: row.get::<_, i64>(0)?,
channel_id: row.get::<_, u32>(1)?,
from: row.get::<_, u32>(2)?,
channel_id: row.get::<_, String>(1)?,
from: row.get::<_, String>(2)?,
contents: row.get::<_, String>(3)?,
timestamp: row.get::<_, i64>(4)?,
})