code cleanup & multi-channel support

This commit is contained in:
2025-10-20 03:45:53 +01:00
parent 07857f1d0a
commit 91ff2e00c4
10 changed files with 304 additions and 82 deletions
+1 -1
View File
@@ -63,7 +63,7 @@ pub async fn signup(
token_id.use_token(&mut db).await?;
println!("phase 5");
return Ok(Redirect::to("/chat"));
Ok(Redirect::to("/chat"))
}
#[get("/login")]
+3 -3
View File
@@ -3,7 +3,7 @@ use rocket::{
http::Status,
outcome::{Outcome, try_outcome},
request::{self, FromRequest},
response::status::{self, BadRequest},
response::status::{self},
serde::json::Json,
};
use rocket_db_pools::Connection;
@@ -50,7 +50,7 @@ pub async fn confirm_totp(
println!("valid");
let totp = totp_gen(mfa.user_id, mfa.secret.as_bytes()).unwrap();
if !totp.check_current(&format!("{}", form.code)).unwrap() {
if !totp.check_current(&form.code.to_string()).unwrap() {
return Err(status::Custom(Status::BadRequest, "Invalid 6-digit code"));
}
@@ -72,7 +72,7 @@ pub async fn confirm_totp(
println!("enabled");
return Ok(());
Ok(())
}
#[get("/totp.jpg")]
+1 -1
View File
@@ -50,7 +50,7 @@ pub struct UploadResponse {
#[post("/profile/<user_id>/upload", data = "<file>")]
pub async fn upload_profile_pic(
user_id: usize,
mut file: Form<TempFile<'_>>,
file: Form<TempFile<'_>>,
) -> Result<Json<UploadResponse>, Status> {
const MAX_FILE_SIZE: u64 = 5 * 1024 * 1024;
if file.len() > MAX_FILE_SIZE {
+1 -1
View File
@@ -32,7 +32,7 @@ impl LlmWorker {
model: "gpt-oss-20b".into(), // whatever model you run locally
messages: vec![Message {
role: "user".into(),
content: message.text.clone().into(),
content: message.text.clone(),
}],
};
+1 -5
View File
@@ -2,18 +2,15 @@
#[macro_use]
extern crate rocket;
use redis::cmd;
use rocket::fs::{FileServer, NamedFile};
use rocket::http::Method;
use rocket::serde::json::Json;
use rocket::{Build, Rocket};
use rocket_cors::{AllowedOrigins, CorsOptions};
use rocket_db_pools::{Connection, Database};
use rocket_db_pools::Database;
use rocket_dyn_templates::Template;
use std::env;
use std::sync::{Arc, LazyLock};
use crate::auth::Session;
use crate::db::{Postgres, Redis};
pub mod auth;
@@ -67,7 +64,6 @@ fn rocket() -> Rocket<Build> {
"/api",
routes![
cdn::upload_profile_pic,
messenger::get_messages,
messenger::post_message,
messenger::event_stream,
user::users,
+4 -6
View File
@@ -51,8 +51,8 @@ pub async fn initialise(
) -> Result<(), Box<dyn std::error::Error>> {
let key = format!("messages:{}", channel_id);
let length: usize = cache.llen(&key).await?;
if length < 100 {
// less than 100 messages in cache?
if cache.llen::<_, i32>(&key).await? < 100 {
// Fetch from Postgres
let messages = sqlx::query!(
"SELECT u.username, u.display_name, u.id, m.content, m.created_at
@@ -68,14 +68,12 @@ pub async fn initialise(
// Populate cache (in reverse order so oldest is at the end)
for msg in messages.into_iter().rev() {
let chat_msg = ChatMsg {
let msg_json = serde_json::to_string(&ChatMsg {
display_name: Some(msg.display_name.unwrap_or(msg.username)),
user_id: msg.id as usize,
text: msg.content,
timestamp: (msg.created_at.unwrap().unix_timestamp_nanos() / 1_000_000) as usize,
};
let msg_json = serde_json::to_string(&chat_msg)?;
})?;
cache.lpush::<_, _, ()>(&key, &msg_json).await?;
}
+4 -7
View File
@@ -16,6 +16,7 @@ use crate::{
auth::Session,
db::{Postgres, Redis},
llm::LlmWorker,
messenger,
};
/// ---------- shared broadcaster ----------
@@ -133,15 +134,11 @@ pub async fn post_message(
Ok(())
}
#[get("/messages")]
pub async fn get_messages(
mut db: Connection<Postgres>,
mut redis: Connection<Redis>,
_session: Session,
channel_id: i32,
) -> Json<Vec<ChatMsg>> {
const CHANNEL_ID: i32 = 1;
let channel_id = CHANNEL_ID;
if let Ok(messages) = messenger::cache::get(&mut redis, channel_id).await
&& !messages.is_empty()
{
@@ -186,7 +183,7 @@ pub async fn event_stream(
chat: &rocket::State<Arc<ChatBroadcaster>>,
postgres: Connection<Postgres>,
cache: Connection<Redis>,
ag: Session,
_session: Session,
mut shutdown: Shutdown,
channel_id: i32,
) -> EventStream![] {
@@ -194,7 +191,7 @@ pub async fn event_stream(
EventStream! {
// Initialize the stream with the last 100 messages
for msg in get_messages(postgres, cache, ag).await.0 {
for msg in get_messages(postgres, cache, channel_id).await.0 {
yield Event::json(&msg);
}
+4 -15
View File
@@ -1,4 +1,4 @@
use redis::cmd;
use redis::AsyncCommands;
use rocket::serde::json::Json;
use rocket_db_pools::Connection;
@@ -37,11 +37,7 @@ impl UserCache {
redis_conn: &mut Connection<Redis>,
pgsql_conn: &mut Connection<Postgres>,
) -> String {
if let Ok(val) = cmd("GET")
.arg(&[format!("users:{id}")])
.query_async(&mut **redis_conn)
.await
{
if let Ok(val) = redis_conn.get(format!("users:{id}")).await {
return val;
}
@@ -58,15 +54,8 @@ impl UserCache {
}
pub async fn insert(id: usize, username: &str, conn: &mut Connection<Redis>) {
cmd("SET")
.arg(&[
format!("users:{id}"),
username.to_string(),
"EX".to_string(),
"1800".to_string(),
])
.query_async(&mut **conn)
conn.set_ex::<_, _, ()>(format!("users:{id}"), username.to_string(), 1800)
.await
.expect("failed to insert key")
.expect("failed to insert key");
}
}