megacommit
@@ -0,0 +1 @@
|
|||||||
|
DATABASE_URL="postgresql://chatapp:chatapp@100.118.108.58:5432/chatapp"
|
||||||
@@ -4,11 +4,16 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
argon2 = "0.5.3"
|
||||||
chrono = { version = "0.4.42", features = ["serde"] }
|
chrono = { version = "0.4.42", features = ["serde"] }
|
||||||
futures-util = "0.3.31"
|
futures-util = "0.3.31"
|
||||||
|
rand = "0.9.2"
|
||||||
reqwest = { version = "0.12.23", features = ["json"] }
|
reqwest = { version = "0.12.23", features = ["json"] }
|
||||||
rocket = { version = "0.5.1", features = ["json"] }
|
rocket = { version = "0.5.1", features = ["json", "secrets"] }
|
||||||
rocket_cors = "0.6.0"
|
rocket_cors = "0.6.0"
|
||||||
rocket_db_pools = { version = "0.2.0", features = ["sqlx_postgres"] }
|
rocket_db_pools = { version = "0.2.0", features = ["sqlx_macros", "sqlx_postgres"] }
|
||||||
|
rocket_dyn_templates = { version = "0.2.0", features = ["tera"] }
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
|
sha2 = "0.10.9"
|
||||||
|
sqlx = { version = "0.7.4", features = ["macros", "time"] }
|
||||||
tokio = { version = "1.47.1", features = ["full"] }
|
tokio = { version = "1.47.1", features = ["full"] }
|
||||||
|
|||||||
@@ -1,2 +1,6 @@
|
|||||||
[debug]
|
[debug]
|
||||||
port = 8001
|
secret_key = "yYhvCGnRh/TrcHtB8sZqCFifrVmJxoKFLBYw/WWBZeU="
|
||||||
|
port = 8000
|
||||||
|
|
||||||
|
[default.databases.postgres_db]
|
||||||
|
url = "postgresql://chatapp:chatapp@100.118.108.58:5432/chatapp"
|
||||||
|
|||||||
|
After Width: | Height: | Size: 1.5 MiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M798-120q-125 0-247-54.5T329-329Q229-429 174.5-551T120-798q0-18 12-30t30-12h162q14 0 25 9.5t13 22.5l26 140q2 16-1 27t-11 19l-97 98q20 37 47.5 71.5T387-386q31 31 65 57.5t72 48.5l94-94q9-9 23.5-13.5T670-390l138 28q14 4 23 14.5t9 23.5v162q0 18-12 30t-30 12ZM241-600l66-66-17-94h-89q5 41 14 81t26 79Zm358 358q39 17 79.5 27t81.5 13v-88l-94-19-67 67ZM241-600Zm358 358Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 487 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M480-360 280-560h400L480-360Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 154 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M480-480q33 0 56.5-23.5T560-560q0-33-23.5-56.5T480-640q-33 0-56.5 23.5T400-560q0 33 23.5 56.5T480-480Zm0 294q122-112 181-203.5T720-552q0-109-69.5-178.5T480-800q-101 0-170.5 69.5T240-552q0 71 59 162.5T480-186Zm0 106Q319-217 239.5-334.5T160-552q0-150 96.5-239T480-880q127 0 223.5 89T800-552q0 100-79.5 217.5T480-80Zm0-480Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 445 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40v280Zm-286 80h252l-46-46v-314H400v314l-46 46Zm126 0Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 258 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 376 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e3e3e3"><path d="M120-160v-640l760 320-760 320Zm80-120 474-200-474-200v140l240 60-240 60v140Zm0 0v-400 400Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 215 B |
|
After Width: | Height: | Size: 671 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 157 KiB |
@@ -0,0 +1,49 @@
|
|||||||
|
-- Add migration script here
|
||||||
|
CREATE TABLE users (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
username VARCHAR(50) UNIQUE NOT NULL,
|
||||||
|
password VARCHAR(50) NOT NULL,
|
||||||
|
display_name VARCHAR(50),
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE channels (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
name VARCHAR(50) NOT NULL,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
is_edited BOOLEAN DEFAULT FALSE
|
||||||
|
);
|
||||||
|
|
||||||
|
create table attachments (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
message_id INTEGER NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||||
|
path TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_messages_channel_id ON messages (channel_id, id DESC);
|
||||||
|
CREATE INDEX idx_new_messages ON messages(created_at DESC);
|
||||||
|
|
||||||
|
-- Create a function to update the updated_at timestamp
|
||||||
|
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.updated_at = CURRENT_TIMESTAMP;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ language 'plpgsql';
|
||||||
|
|
||||||
|
-- Create trigger for messages table
|
||||||
|
CREATE TRIGGER update_messages_updated_at
|
||||||
|
BEFORE UPDATE ON messages
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION update_updated_at_column();
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- Add migration script here
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
token TEXT NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + INTERVAL '7 days'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION cleanup_expired_sessions()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
DELETE FROM sessions WHERE expires_at < NOW();
|
||||||
|
RETURN NULL;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
CREATE TRIGGER trigger_cleanup_sessions
|
||||||
|
AFTER INSERT ON sessions
|
||||||
|
EXECUTE FUNCTION cleanup_expired_sessions();
|
||||||
@@ -1,6 +1,21 @@
|
|||||||
use rocket::{post, serde::json::Json};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use rocket_db_pools::{Connection, Database, sqlx};
|
|
||||||
|
use rand::Rng;
|
||||||
|
use rocket::{
|
||||||
|
Request,
|
||||||
|
http::{CookieJar, Status},
|
||||||
|
outcome::Outcome,
|
||||||
|
post,
|
||||||
|
request::{self, FromRequest},
|
||||||
|
serde::json::Json,
|
||||||
|
};
|
||||||
|
use rocket_db_pools::{
|
||||||
|
Connection, Database,
|
||||||
|
sqlx::{self},
|
||||||
|
};
|
||||||
|
use rocket_dyn_templates::{Template, context};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
#[derive(Database)]
|
#[derive(Database)]
|
||||||
#[database("postgres_db")]
|
#[database("postgres_db")]
|
||||||
@@ -14,12 +29,44 @@ pub struct UserCredentials {
|
|||||||
|
|
||||||
#[post("/signup", data = "<cred>")]
|
#[post("/signup", data = "<cred>")]
|
||||||
pub async fn signup(
|
pub async fn signup(
|
||||||
conn: Connection<DbConn>,
|
|
||||||
cred: Json<UserCredentials>,
|
cred: Json<UserCredentials>,
|
||||||
|
jar: &CookieJar<'_>,
|
||||||
|
mut db: Connection<DbConn>,
|
||||||
) -> Result<Json<String>, String> {
|
) -> Result<Json<String>, String> {
|
||||||
|
let result = sqlx::query!(
|
||||||
|
"INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id",
|
||||||
|
cred.username,
|
||||||
|
cred.password
|
||||||
|
)
|
||||||
|
.fetch_one(&mut **db)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let session = SessionToken::new(result.id as usize);
|
||||||
|
let result = sqlx::query!(
|
||||||
|
"INSERT INTO sessions (user_id, token) VALUES ($1, $2)",
|
||||||
|
result.id,
|
||||||
|
session.token,
|
||||||
|
)
|
||||||
|
.execute(&mut **db)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if let Err(e) = result {
|
||||||
|
eprintln!("Failed to create session: {}", e);
|
||||||
|
return Err(e.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
jar.add_private(("session", session.token));
|
||||||
|
|
||||||
|
println!("Signup successful");
|
||||||
Ok(Json("Signup successful".to_string()))
|
Ok(Json("Signup successful".to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[get("/signup")]
|
||||||
|
pub async fn signup_page() -> Template {
|
||||||
|
Template::render("signup", context!())
|
||||||
|
}
|
||||||
|
|
||||||
#[post("/login", data = "<cred>")]
|
#[post("/login", data = "<cred>")]
|
||||||
pub async fn login(
|
pub async fn login(
|
||||||
conn: Connection<DbConn>,
|
conn: Connection<DbConn>,
|
||||||
@@ -28,3 +75,58 @@ pub async fn login(
|
|||||||
// TODO: implement actual login logic, e.g. verify password and generate token
|
// TODO: implement actual login logic, e.g. verify password and generate token
|
||||||
Ok(Json("Login successful".to_string()))
|
Ok(Json("Login successful".to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct SessionToken {
|
||||||
|
pub token: String,
|
||||||
|
pub user_id: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SessionToken {
|
||||||
|
pub fn new(user_id: usize) -> Self {
|
||||||
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||||
|
let random: u32 = rand::rng().random();
|
||||||
|
let token = format!("{}-{}", current_time.as_secs(), random);
|
||||||
|
let hashed = format!("{:x}", Sha256::digest(token.as_bytes()));
|
||||||
|
SessionToken {
|
||||||
|
token: hashed,
|
||||||
|
user_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserID = usize;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct AuthGuard(pub UserID);
|
||||||
|
|
||||||
|
#[rocket::async_trait]
|
||||||
|
impl<'r> FromRequest<'r> for AuthGuard {
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||||
|
if let Some(c) = request.cookies().get_private("session") {
|
||||||
|
let mut pool = match request.guard::<Connection<DbConn>>().await {
|
||||||
|
Outcome::Success(pool) => pool,
|
||||||
|
_ => return Outcome::Error((Status::Unauthorized, ())),
|
||||||
|
};
|
||||||
|
|
||||||
|
let value = c.value();
|
||||||
|
let result = sqlx::query!(
|
||||||
|
"SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()",
|
||||||
|
value
|
||||||
|
)
|
||||||
|
.fetch_optional(&mut **pool)
|
||||||
|
.await
|
||||||
|
.expect("query failed!");
|
||||||
|
|
||||||
|
if let Some(token) = result {
|
||||||
|
let user_id = token.user_id;
|
||||||
|
Outcome::Success(AuthGuard(user_id as usize))
|
||||||
|
} else {
|
||||||
|
Outcome::Error((Status::Unauthorized, ()))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Outcome::Error((Status::Unauthorized, ()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use rocket::fs::NamedFile;
|
||||||
|
|
||||||
|
pub fn routes() -> Vec<rocket::Route> {
|
||||||
|
routes![profile_pic, general]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/profile/<user_id>")]
|
||||||
|
pub async fn profile_pic(user_id: usize) -> Option<NamedFile> {
|
||||||
|
if let Ok(image) =
|
||||||
|
NamedFile::open(Path::new("./cdn/profiles/").join(format!("{}.jpg", user_id))).await
|
||||||
|
{
|
||||||
|
Some(image)
|
||||||
|
} else {
|
||||||
|
Some(NamedFile::open("./cdn/profiles/default.jpg").await.ok()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/<file_name..>")]
|
||||||
|
pub async fn general(file_name: PathBuf) -> Option<NamedFile> {
|
||||||
|
NamedFile::open(Path::new("./cdn/").join(file_name))
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
// src/llm.rs
|
// src/llm.rs
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::messages::ChatMsg;
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct LlmRequest {
|
struct LlmRequest {
|
||||||
model: String,
|
model: String,
|
||||||
@@ -13,36 +15,51 @@ struct Message {
|
|||||||
content: String,
|
content: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn query_llm(text: &str) -> Result<String, String> {
|
pub struct LlmWorker {
|
||||||
let client = reqwest::Client::new();
|
uri: String,
|
||||||
|
}
|
||||||
// Build the request body
|
|
||||||
let payload = LlmRequest {
|
impl LlmWorker {
|
||||||
model: "gemma2-9b-it".into(), // whatever model you run locally
|
pub fn new(uri: String) -> Self {
|
||||||
messages: vec![Message {
|
Self { uri }
|
||||||
role: "user".into(),
|
}
|
||||||
content: text.into(),
|
|
||||||
}],
|
pub async fn query(&self, message: &ChatMsg) -> Result<ChatMsg, String> {
|
||||||
};
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
// POST to lm‑studio (default 127.0.0.1:1234)
|
// Build the request body
|
||||||
let resp = client
|
let payload = LlmRequest {
|
||||||
.post("http://127.0.0.1:1234/v1/chat/completions")
|
model: "gemma2-9b-it".into(), // whatever model you run locally
|
||||||
.json(&payload)
|
messages: vec![Message {
|
||||||
.send()
|
role: "user".into(),
|
||||||
.await
|
content: message.text.clone().into(),
|
||||||
.unwrap();
|
}],
|
||||||
|
};
|
||||||
// The API returns a JSON with `choices[].message.content`
|
|
||||||
#[derive(Deserialize)]
|
// POST to lm‑studio (default 127.0.0.1:1234)
|
||||||
struct LlmResponse {
|
let resp = client
|
||||||
choices: Vec<Choice>,
|
.post(self.uri.clone())
|
||||||
}
|
.json(&payload)
|
||||||
#[derive(Deserialize)]
|
.send()
|
||||||
struct Choice {
|
.await
|
||||||
message: Message,
|
.unwrap();
|
||||||
}
|
|
||||||
|
// The API returns a JSON with `choices[].message.content`
|
||||||
let llm_resp: LlmResponse = resp.json().await.unwrap();
|
#[derive(Deserialize)]
|
||||||
Ok(llm_resp.choices[0].message.content.clone())
|
struct LlmResponse {
|
||||||
|
choices: Vec<Choice>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Choice {
|
||||||
|
message: Message,
|
||||||
|
}
|
||||||
|
|
||||||
|
let llm_resp: LlmResponse = resp.json().await.unwrap();
|
||||||
|
|
||||||
|
Ok(ChatMsg {
|
||||||
|
user_id: 0,
|
||||||
|
text: llm_resp.choices[0].message.content.clone(),
|
||||||
|
timestamp: chrono::Local::now().timestamp() as usize,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,134 +3,44 @@
|
|||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
|
|
||||||
use rocket::fairing::Fairing;
|
use rocket::fairing::Fairing;
|
||||||
|
use rocket::fs::FileServer;
|
||||||
use rocket::http::Method;
|
use rocket::http::Method;
|
||||||
use rocket::response::stream::{Event, EventStream};
|
use rocket::response::stream::{Event, EventStream};
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
use rocket::{Build, Rocket};
|
use rocket::{Build, Rocket};
|
||||||
use rocket_cors::{AllowedOrigins, CorsOptions};
|
use rocket_cors::{AllowedOrigins, CorsOptions};
|
||||||
|
use rocket_db_pools::{Connection, Database};
|
||||||
|
use rocket_dyn_templates::{Template, context};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::broadcast;
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
use crate::llm::query_llm;
|
use crate::auth::{AuthGuard, DbConn};
|
||||||
|
use crate::llm::LlmWorker;
|
||||||
|
use crate::messages::ChatBroadcaster;
|
||||||
|
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
|
pub mod cdn;
|
||||||
pub mod llm;
|
pub mod llm;
|
||||||
|
pub mod messages;
|
||||||
|
|
||||||
/// ---------- shared broadcaster ----------
|
#[get("/users", rank = 2)]
|
||||||
struct ChatBroadcaster {
|
async fn users(_ag: AuthGuard, mut db: Connection<DbConn>) -> Json<Vec<i32>> {
|
||||||
sender: broadcast::Sender<ChatMsg>,
|
sqlx::query!("SELECT id FROM users")
|
||||||
|
.fetch_all(&mut **db)
|
||||||
|
.await
|
||||||
|
.map(|rows| rows.into_iter().map(|row| row.id).collect())
|
||||||
|
.unwrap_or_else(|_| Vec::new())
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChatBroadcaster {
|
#[get("/users/<id>", rank = 1)]
|
||||||
fn new(buffer_size: usize) -> Self {
|
async fn username_for_id(id: usize, _ag: AuthGuard, mut db: Connection<DbConn>) -> String {
|
||||||
let (sender, _rx) = broadcast::channel::<ChatMsg>(buffer_size);
|
sqlx::query!("SELECT username FROM users WHERE id = $1", id as i32)
|
||||||
Self { sender }
|
.fetch_one(&mut **db)
|
||||||
}
|
.await
|
||||||
|
.map(|row| row.username)
|
||||||
async fn publish(&self, msg: ChatMsg) {
|
.unwrap_or_else(|_| "User not found".to_string())
|
||||||
let _ = self.sender.send(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscribe(&self) -> broadcast::Receiver<ChatMsg> {
|
|
||||||
self.sender.subscribe()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// ---------- Rocket routes ----------
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct ChatMsg {
|
|
||||||
userid: usize,
|
|
||||||
text: String,
|
|
||||||
timestamp: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/chat", format = "json", data = "<msg>")]
|
|
||||||
async fn post_message(
|
|
||||||
msg: Json<ChatMsg>,
|
|
||||||
chat: &rocket::State<Arc<ChatBroadcaster>>,
|
|
||||||
) -> &'static str {
|
|
||||||
chat.publish(msg.into_inner()).await;
|
|
||||||
"Message sent"
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/events")]
|
|
||||||
async fn event_stream(chat: &rocket::State<Arc<ChatBroadcaster>>) -> EventStream![] {
|
|
||||||
let mut rx = chat.subscribe();
|
|
||||||
|
|
||||||
EventStream! {
|
|
||||||
loop {
|
|
||||||
match rx.recv().await {
|
|
||||||
Ok(msg) => yield Event::json(&msg),
|
|
||||||
Err(broadcast::error::RecvError::Lagged(_)) => {
|
|
||||||
yield Event::comment("lagged");
|
|
||||||
}
|
|
||||||
Err(broadcast::error::RecvError::Closed) => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------- LLM worker ----------
|
|
||||||
async fn start_llm_worker(chat: Arc<ChatBroadcaster>) {
|
|
||||||
let mut rx = chat.subscribe();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
match rx.recv().await {
|
|
||||||
Ok(msg) => {
|
|
||||||
if msg.userid == 0 {
|
|
||||||
// ignore bot messages
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let user_text = msg.text.clone();
|
|
||||||
let chat_clone = chat.clone();
|
|
||||||
|
|
||||||
rocket::tokio::spawn(async move {
|
|
||||||
match query_llm(&user_text).await {
|
|
||||||
Ok(reply) => {
|
|
||||||
let bot_msg = ChatMsg {
|
|
||||||
userid: 0,
|
|
||||||
text: reply,
|
|
||||||
timestamp: chrono::Local::now().timestamp() as usize,
|
|
||||||
};
|
|
||||||
chat_clone.publish(bot_msg).await;
|
|
||||||
}
|
|
||||||
Err(e) => eprintln!("LLM error: {}", e),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Err(_) => break, // channel closed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct LlmWorkerFairing;
|
|
||||||
|
|
||||||
#[rocket::async_trait]
|
|
||||||
impl Fairing for LlmWorkerFairing {
|
|
||||||
fn info(&self) -> rocket::fairing::Info {
|
|
||||||
rocket::fairing::Info {
|
|
||||||
name: "LLM background worker",
|
|
||||||
kind: rocket::fairing::Kind::Ignite,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_ignite(&self, rocket: Rocket<Build>) -> rocket::fairing::Result {
|
|
||||||
// Grab the shared broadcaster from state
|
|
||||||
let chat = rocket
|
|
||||||
.state::<Arc<ChatBroadcaster>>()
|
|
||||||
.expect("ChatBroadcaster not managed");
|
|
||||||
// Clone it so we can move into async block
|
|
||||||
let chat_clone = Arc::clone(chat);
|
|
||||||
|
|
||||||
// Spawn the background worker **inside** on_ignite
|
|
||||||
tokio::spawn(async move {
|
|
||||||
start_llm_worker(chat_clone).await;
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(rocket)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// ---------- launch ----------
|
/// ---------- launch ----------
|
||||||
@@ -151,9 +61,22 @@ fn rocket() -> Rocket<Build> {
|
|||||||
rocket::build()
|
rocket::build()
|
||||||
.manage(chat)
|
.manage(chat)
|
||||||
.attach(cors.to_cors().unwrap())
|
.attach(cors.to_cors().unwrap())
|
||||||
.attach(LlmWorkerFairing {})
|
.attach(DbConn::init())
|
||||||
|
.attach(Template::fairing())
|
||||||
|
.mount("/static", FileServer::from("static"))
|
||||||
|
.mount("/cdn", cdn::routes())
|
||||||
.mount(
|
.mount(
|
||||||
"/",
|
"/",
|
||||||
routes![post_message, event_stream, auth::signup, auth::login],
|
routes![
|
||||||
|
users,
|
||||||
|
username_for_id,
|
||||||
|
messages::chat_page,
|
||||||
|
messages::get_messages,
|
||||||
|
messages::post_message,
|
||||||
|
messages::event_stream,
|
||||||
|
auth::signup,
|
||||||
|
auth::signup_page,
|
||||||
|
auth::login
|
||||||
|
],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use rocket::{
|
||||||
|
response::stream::{Event, EventStream},
|
||||||
|
serde::json::Json,
|
||||||
|
};
|
||||||
|
use rocket_db_pools::Connection;
|
||||||
|
use rocket_dyn_templates::{Template, context};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
auth::{AuthGuard, DbConn},
|
||||||
|
llm::LlmWorker,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// ---------- shared broadcaster ----------
|
||||||
|
pub struct ChatBroadcaster {
|
||||||
|
sender: broadcast::Sender<ChatMsg>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChatBroadcaster {
|
||||||
|
pub fn new(buffer_size: usize) -> Self {
|
||||||
|
let (sender, _rx) = broadcast::channel::<ChatMsg>(buffer_size);
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn publish(&self, msg: ChatMsg) {
|
||||||
|
let _ = self.sender.send(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subscribe(&self) -> broadcast::Receiver<ChatMsg> {
|
||||||
|
self.sender.subscribe()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ---------- Rocket routes ----------
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
pub struct ChatMsg {
|
||||||
|
pub user_id: usize,
|
||||||
|
pub text: String,
|
||||||
|
pub timestamp: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/chat", format = "json", data = "<msg>")]
|
||||||
|
pub async fn post_message(
|
||||||
|
mut msg: Json<ChatMsg>,
|
||||||
|
chat: &rocket::State<Arc<ChatBroadcaster>>,
|
||||||
|
mut db: Connection<DbConn>,
|
||||||
|
ag: AuthGuard,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
const CHANNEL_ID: i32 = 1;
|
||||||
|
const LMSTUDIO_URI: &'static str = "http://127.0.0.1:1234/v1/chat/completions";
|
||||||
|
|
||||||
|
let chat = chat.inner().clone();
|
||||||
|
|
||||||
|
msg.user_id = ag.0;
|
||||||
|
chat.publish(msg.clone().into_inner()).await;
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"INSERT INTO messages (channel_id, user_id, content) VALUES ($1, $2, $3)",
|
||||||
|
CHANNEL_ID,
|
||||||
|
msg.user_id as i32,
|
||||||
|
msg.text
|
||||||
|
)
|
||||||
|
.execute(&mut **db)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "Failed".to_string())?;
|
||||||
|
|
||||||
|
// get response
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let response = LlmWorker::new(LMSTUDIO_URI.to_string()).query(&msg).await;
|
||||||
|
|
||||||
|
if let Ok(message) = response {
|
||||||
|
chat.publish(message.clone()).await;
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"INSERT INTO messages (channel_id, user_id, content) VALUES ($1, $2, $3)",
|
||||||
|
CHANNEL_ID,
|
||||||
|
message.user_id as i32,
|
||||||
|
message.text
|
||||||
|
)
|
||||||
|
.execute(&mut **db)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "Failed".to_string())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/messages")]
|
||||||
|
pub async fn get_messages(mut db: Connection<DbConn>, _ag: AuthGuard) -> Json<Vec<ChatMsg>> {
|
||||||
|
Json(
|
||||||
|
sqlx::query!(
|
||||||
|
"SELECT user_id, content, created_at FROM messages ORDER BY created_at DESC LIMIT 100"
|
||||||
|
)
|
||||||
|
.fetch_all(&mut **db)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| Vec::new())
|
||||||
|
.into_iter()
|
||||||
|
.rev()
|
||||||
|
.map(|row| ChatMsg {
|
||||||
|
user_id: row.user_id as usize,
|
||||||
|
text: row.content,
|
||||||
|
timestamp: row.created_at.unwrap().unix_timestamp() as usize,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/events")]
|
||||||
|
pub async fn event_stream(
|
||||||
|
chat: &rocket::State<Arc<ChatBroadcaster>>,
|
||||||
|
_ag: AuthGuard,
|
||||||
|
) -> EventStream![] {
|
||||||
|
let mut rx = chat.subscribe();
|
||||||
|
|
||||||
|
EventStream! {
|
||||||
|
loop {
|
||||||
|
match rx.recv().await {
|
||||||
|
Ok(msg) => yield Event::json(&msg),
|
||||||
|
Err(broadcast::error::RecvError::Lagged(_)) => {
|
||||||
|
yield Event::comment("lagged");
|
||||||
|
}
|
||||||
|
Err(broadcast::error::RecvError::Closed) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
pub async fn chat_page(ag: AuthGuard) -> Template {
|
||||||
|
Template::render("chat", context!(user_id: ag.0))
|
||||||
|
}
|
||||||
@@ -0,0 +1,774 @@
|
|||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
background: #0a0a0a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100vh;
|
||||||
|
max-width: 50vh;
|
||||||
|
margin: 0 auto;
|
||||||
|
background: #121212;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Chat Header */
|
||||||
|
.chat-header {
|
||||||
|
padding: 10px;
|
||||||
|
background: #1a1a1a;
|
||||||
|
border-bottom: 1px solid #252525;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-dot {
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
background: #ff4444;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: pulse 2s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: scale(1);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: scale(1.3);
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-title h1 {
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Live Location Notification Bubble */
|
||||||
|
.notification-container {
|
||||||
|
padding: 15px 20px 10px 20px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
position: absolute;
|
||||||
|
top: 70px;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
z-index: 10;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble {
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 20px;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
|
border: 1px solid rgba(138, 43, 226, 0.3);
|
||||||
|
box-shadow:
|
||||||
|
0 8px 32px rgba(106, 90, 205, 0.2),
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||||
|
pointer-events: auto;
|
||||||
|
max-height: 64px;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: linear-gradient(
|
||||||
|
135deg,
|
||||||
|
rgba(106, 90, 205, 0.25) 0%,
|
||||||
|
rgba(72, 61, 139, 0.2) 50%,
|
||||||
|
rgba(123, 104, 238, 0.15) 100%
|
||||||
|
);
|
||||||
|
backdrop-filter: blur(20px);
|
||||||
|
-webkit-backdrop-filter: blur(20px);
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded::before {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble > * {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded {
|
||||||
|
max-height: 400px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 0;
|
||||||
|
opacity: 0;
|
||||||
|
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded .map-container {
|
||||||
|
height: 260px;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-container img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
background: linear-gradient(
|
||||||
|
135deg,
|
||||||
|
rgba(106, 90, 205, 0.25) 0%,
|
||||||
|
rgba(72, 61, 139, 0.2) 50%,
|
||||||
|
rgba(123, 104, 238, 0.15) 100%
|
||||||
|
);
|
||||||
|
backdrop-filter: blur(20px);
|
||||||
|
-webkit-backdrop-filter: blur(20px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded .location-content {
|
||||||
|
background: linear-gradient(
|
||||||
|
to bottom,
|
||||||
|
rgba(106, 90, 205, 0.45) 0%,
|
||||||
|
rgba(72, 61, 139, 0.4) 50%,
|
||||||
|
rgba(123, 104, 238, 0.35) 100%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
height: 1px;
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
transparent,
|
||||||
|
rgba(255, 255, 255, 0.2),
|
||||||
|
transparent
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow:
|
||||||
|
0 12px 40px rgba(106, 90, 205, 0.35),
|
||||||
|
inset 0 1px 0 rgba(255, 255, 255, 0.15);
|
||||||
|
background: linear-gradient(
|
||||||
|
135deg,
|
||||||
|
rgba(106, 90, 205, 0.3) 0%,
|
||||||
|
rgba(72, 61, 139, 0.25) 50%,
|
||||||
|
rgba(123, 104, 238, 0.2) 100%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.active {
|
||||||
|
background: linear-gradient(
|
||||||
|
135deg,
|
||||||
|
rgba(106, 90, 205, 0.35) 0%,
|
||||||
|
rgba(72, 61, 139, 0.3) 50%,
|
||||||
|
rgba(123, 104, 238, 0.25) 100%
|
||||||
|
);
|
||||||
|
border-color: rgba(138, 43, 226, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-icon {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
background: rgba(255, 255, 255, 0.15);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-icon svg {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
fill: #ea4335;
|
||||||
|
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded .location-icon {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.join-button {
|
||||||
|
display: none;
|
||||||
|
padding: 8px 20px;
|
||||||
|
background: rgba(255, 255, 255, 0.15);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
border-radius: 20px;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.expanded .join-button {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.join-button:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.25);
|
||||||
|
transform: scale(1.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.join-button:active {
|
||||||
|
transform: scale(0.95);
|
||||||
|
}
|
||||||
|
|
||||||
|
.join-button.active {
|
||||||
|
background: rgba(106, 90, 205, 0.4);
|
||||||
|
border-color: rgba(138, 43, 226, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.live-location-bubble.active .location-icon {
|
||||||
|
background: rgba(255, 255, 255, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-text {
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #ffffff;
|
||||||
|
flex: 1;
|
||||||
|
letter-spacing: 0.3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-users {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-user-pic {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 35%;
|
||||||
|
margin-left: -15px;
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-user-pic:first-child {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-user-pic:hover {
|
||||||
|
z-index: 10;
|
||||||
|
transform: scale(1.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.location-count {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 35%;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
margin-left: -15px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #ffffff;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-container::before {
|
||||||
|
content: "";
|
||||||
|
flex: 1 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Messages Container */
|
||||||
|
.messages-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
/*justify-content: flex-end;*/
|
||||||
|
flex: 1;
|
||||||
|
padding: 15px 0 15px 0;
|
||||||
|
overflow-y: scroll;
|
||||||
|
background: #121212;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
margin: 10px 20px;
|
||||||
|
padding: 10px 10px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: rgba(30, 30, 30, 0.4);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border: 1px solid #252525;
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message:hover {
|
||||||
|
background: #1f1f1f;
|
||||||
|
border-color: #2a2a2a;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes slideIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(10px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-avatar {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
border-radius: 25%;
|
||||||
|
background-size: cover;
|
||||||
|
border: 2px solid #252525;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background-image: url("static/profile_pics/default.jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-avatar.blue {
|
||||||
|
background: linear-gradient(135deg, #4169e1, #6495ed);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 15px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timestamp {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #666;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-text {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #b0b0b0;
|
||||||
|
line-height: 1.4;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Input Container */
|
||||||
|
.input-container {
|
||||||
|
padding: 10px;
|
||||||
|
background: #1a1a1a;
|
||||||
|
border-top: 1px solid #252525;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
background: #252525;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 5px 5px;
|
||||||
|
border: 1px solid #2a2a2a;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper:focus-within {
|
||||||
|
background: #2a2a2a;
|
||||||
|
border-color: #6a5acd;
|
||||||
|
box-shadow: 0 0 0 3px rgba(106, 90, 205, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper input {
|
||||||
|
flex: 1;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 14px;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper input::placeholder {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-button {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
background: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-button:hover {
|
||||||
|
transform: scale(1.1);
|
||||||
|
box-shadow: 0 4px 15px rgba(106, 90, 205, 0.4);
|
||||||
|
background: rgba(255, 255, 255, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.send-button:active {
|
||||||
|
transform: scale(0.95);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Scrollbar styling */
|
||||||
|
.messages-container::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-container::-webkit-scrollbar-track {
|
||||||
|
background: #1a1a1a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-container::-webkit-scrollbar-thumb {
|
||||||
|
background: #333;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages-container::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
background: #0a0a0a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-container {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 480px;
|
||||||
|
background: #121212;
|
||||||
|
border-radius: 16px;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||||
|
animation: slideIn 0.4s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes slideIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(20px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-header {
|
||||||
|
padding: 40px 40px 30px;
|
||||||
|
text-align: center;
|
||||||
|
background: linear-gradient(
|
||||||
|
135deg,
|
||||||
|
rgba(106, 90, 205, 0.15) 0%,
|
||||||
|
rgba(72, 61, 139, 0.1) 100%
|
||||||
|
);
|
||||||
|
border-bottom: 1px solid #252525;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
width: 80px;
|
||||||
|
height: 80px;
|
||||||
|
margin: 0 auto 20px;
|
||||||
|
background: linear-gradient(135deg, #6a5acd, #483d8b);
|
||||||
|
border-radius: 25%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 36px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #ffffff;
|
||||||
|
box-shadow: 0 4px 16px rgba(106, 90, 205, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-header h1 {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #ffffff;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-header p {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-form {
|
||||||
|
padding: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #b0b0b0;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-wrapper {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: #1a1a1a;
|
||||||
|
border: 1px solid #252525;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-size: 15px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus {
|
||||||
|
background: #1f1f1f;
|
||||||
|
border-color: #6a5acd;
|
||||||
|
box-shadow: 0 0 0 3px rgba(106, 90, 205, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input::placeholder {
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
display: none;
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #ff4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group.error input {
|
||||||
|
border-color: #ff4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group.error .error-message {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.password-toggle {
|
||||||
|
position: absolute;
|
||||||
|
right: 12px;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: #666;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.password-toggle:hover {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 14px;
|
||||||
|
background: linear-gradient(135deg, #6a5acd, #483d8b);
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
box-shadow: 0 4px 16px rgba(106, 90, 205, 0.3);
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button:hover {
|
||||||
|
background: linear-gradient(135deg, #7b6bd8, #5a4ea0);
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 6px 20px rgba(106, 90, 205, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button:active {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit-button:disabled {
|
||||||
|
background: #2a2a2a;
|
||||||
|
color: #555;
|
||||||
|
cursor: not-allowed;
|
||||||
|
transform: none;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-footer {
|
||||||
|
padding: 20px 40px 30px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 14px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-footer a {
|
||||||
|
color: #6a5acd;
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signup-footer a:hover {
|
||||||
|
color: #7b6bd8;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-message {
|
||||||
|
display: none;
|
||||||
|
padding: 16px;
|
||||||
|
background: rgba(76, 175, 80, 0.1);
|
||||||
|
border: 1px solid rgba(76, 175, 80, 0.3);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: #4caf50;
|
||||||
|
font-size: 14px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-message.show {
|
||||||
|
display: block;
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-spinner {
|
||||||
|
display: inline-block;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||||
|
border-top-color: #ffffff;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 0.6s linear infinite;
|
||||||
|
margin-right: 8px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group input[type="checkbox"] {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
margin-top: 2px;
|
||||||
|
cursor: pointer;
|
||||||
|
accent-color: #6a5acd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group label {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #888;
|
||||||
|
line-height: 1.5;
|
||||||
|
text-transform: none;
|
||||||
|
letter-spacing: normal;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group a {
|
||||||
|
color: #6a5acd;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Discord Clone - Group Chat</title>
|
||||||
|
<link rel="stylesheet" href="static/css/index.css"/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="chat-container">
|
||||||
|
<!--<div class="chat-container" style="background-image: url('cdn/background.png'); backdrop-filter: blur(10px); background-size: cover; background-position: center; background-repeat: no-repeat;">-->
|
||||||
|
<!-- Chat Header -->
|
||||||
|
<div class="chat-header">
|
||||||
|
<div class="chat-title">
|
||||||
|
<img class="user-avatar" src="cdn/profile/0"></img>
|
||||||
|
<h1>Chat title</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Live Location Notification Bubble -->
|
||||||
|
<div class="notification-container">
|
||||||
|
<div class="live-location-bubble" id="locationBubble">
|
||||||
|
<div class="map-container">
|
||||||
|
<img src="cdn/map.png" alt="Map" />
|
||||||
|
</div>
|
||||||
|
<div class="location-content">
|
||||||
|
<div class="location-icon">
|
||||||
|
<img src="cdn/icons/location.svg" alt="Location"></img>
|
||||||
|
</div>
|
||||||
|
<button class="join-button" id="joinButton">
|
||||||
|
Join
|
||||||
|
</button>
|
||||||
|
<div class="location-text">Live Location</div>
|
||||||
|
<div class="location-users" id="locationUsers">
|
||||||
|
<!-- Users will be added dynamically -->
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Messages Container -->
|
||||||
|
<!--<div class="messages-container" style="background-image: url('cdn/background.png'); backdrop-filter: blur(10px); background-size: cover; background-position: center; background-repeat: no-repeat;">-->
|
||||||
|
<div class="messages-container"></div>
|
||||||
|
|
||||||
|
<!-- Input Container -->
|
||||||
|
<div class="input-container">
|
||||||
|
<div class="input-wrapper">
|
||||||
|
<input type="text" placeholder="Start Typing..." />
|
||||||
|
<button class="send-button">
|
||||||
|
<img src="cdn/icons/send.svg" alt="Send" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const user_id = {{ user_id }};
|
||||||
|
var users = {};
|
||||||
|
|
||||||
|
// Location tracker state
|
||||||
|
const locationUsers = [
|
||||||
|
{ id: 1, color: "linear-gradient(135deg, #ff6b6b, #ff8e8e)" },
|
||||||
|
{ id: 2, color: "linear-gradient(135deg, #4ecdc4, #7fdbda)" },
|
||||||
|
{ id: 3, color: "linear-gradient(135deg, #45b7d1, #6cc5e0)" },
|
||||||
|
];
|
||||||
|
|
||||||
|
let hiddenUsersCount = 5; // Users not shown in the visible stack
|
||||||
|
let currentUserInLocation = false;
|
||||||
|
|
||||||
|
function updateLocationUsers() {
|
||||||
|
const container = document.getElementById("locationUsers");
|
||||||
|
container.innerHTML = "";
|
||||||
|
|
||||||
|
const maxVisible = 3;
|
||||||
|
const visibleUsers = locationUsers.slice(0, maxVisible);
|
||||||
|
|
||||||
|
visibleUsers.forEach((user) => {
|
||||||
|
const pic = document.createElement("div");
|
||||||
|
pic.className = "location-user-pic";
|
||||||
|
pic.style.background = user.color;
|
||||||
|
container.appendChild(pic);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate total hidden users (hidden users + current user if tracking)
|
||||||
|
const totalHidden =
|
||||||
|
hiddenUsersCount + (currentUserInLocation ? 1 : 0);
|
||||||
|
|
||||||
|
// Add count indicator if there are more users
|
||||||
|
if (totalHidden > 0) {
|
||||||
|
const count = document.createElement("div");
|
||||||
|
count.className = "location-count";
|
||||||
|
count.textContent = `+${totalHidden}`;
|
||||||
|
container.appendChild(count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Toggle location tracking
|
||||||
|
const locationBubble = document.getElementById("locationBubble");
|
||||||
|
const joinButton = document.getElementById("joinButton");
|
||||||
|
let isExpanded = false;
|
||||||
|
|
||||||
|
locationBubble.addEventListener("click", function (e) {
|
||||||
|
// Don't toggle expanded state if clicking the join button
|
||||||
|
if (e.target.id === "joinButton") return;
|
||||||
|
|
||||||
|
isExpanded = !isExpanded;
|
||||||
|
this.classList.toggle("expanded", isExpanded);
|
||||||
|
});
|
||||||
|
|
||||||
|
joinButton.addEventListener("click", function (e) {
|
||||||
|
e.stopPropagation();
|
||||||
|
currentUserInLocation = !currentUserInLocation;
|
||||||
|
this.classList.toggle("active", currentUserInLocation);
|
||||||
|
this.textContent = currentUserInLocation ? "Leave" : "Join";
|
||||||
|
locationBubble.classList.toggle(
|
||||||
|
"active",
|
||||||
|
currentUserInLocation,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Animate click
|
||||||
|
this.style.transform = "scale(0.95)";
|
||||||
|
setTimeout(() => {
|
||||||
|
this.style.transform = "";
|
||||||
|
}, 150);
|
||||||
|
|
||||||
|
updateLocationUsers();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initialize location users
|
||||||
|
updateLocationUsers();
|
||||||
|
|
||||||
|
// Handle message sending
|
||||||
|
const input = document.querySelector("input");
|
||||||
|
const sendButton = document.querySelector(".send-button");
|
||||||
|
const messagesContainer = document.querySelector(
|
||||||
|
".messages-container",
|
||||||
|
);
|
||||||
|
const messageSource = new EventSource("http://localhost:8000/events");
|
||||||
|
|
||||||
|
function insertMessage(message) {
|
||||||
|
const date = new Date(message.timestamp).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
});
|
||||||
|
console.log(users, message);
|
||||||
|
|
||||||
|
const uid = message.user_id;
|
||||||
|
const uname = users[`${uid}`];
|
||||||
|
|
||||||
|
console.log(users, uid, uname);
|
||||||
|
|
||||||
|
const messageEl = document.createElement("div");
|
||||||
|
messageEl.className = "message";
|
||||||
|
messageEl.innerHTML = `
|
||||||
|
<img class="user-avatar" src="cdn/profile/${uid}">
|
||||||
|
<div class="message-content">
|
||||||
|
<div class="message-header">
|
||||||
|
<span class="username">${uname}</span>
|
||||||
|
<span class="timestamp">${date}</span>
|
||||||
|
</div>
|
||||||
|
<div class="message-text">${message.text}</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
messagesContainer.appendChild(messageEl);
|
||||||
|
messagesContainer.scrollTop =
|
||||||
|
messagesContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageSource.onmessage = (event) => insertMessage(JSON.parse(event.data));
|
||||||
|
|
||||||
|
function getCurrentTime() {
|
||||||
|
const now = new Date();
|
||||||
|
return now.toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendMessage() {
|
||||||
|
const message = input.value.trim();
|
||||||
|
if (message) {
|
||||||
|
fetch("http://localhost:8000/chat", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
userid: user_id,
|
||||||
|
text: message,
|
||||||
|
timestamp: new Date().getTime(),
|
||||||
|
}),
|
||||||
|
headers: {
|
||||||
|
"Content-type": "application/json; charset=UTF-8"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
input.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendButton.addEventListener("click", sendMessage);
|
||||||
|
input.addEventListener("keypress", function (e) {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
sendMessage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// get previous messages
|
||||||
|
fetch("http://localhost:8000/messages")
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(messages => {
|
||||||
|
messages.forEach(message => {
|
||||||
|
insertMessage(message);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fetch("http://localhost:8000/users/")
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(items => {
|
||||||
|
items.forEach(user => {
|
||||||
|
fetch(`http://localhost:8000/users/${user}`)
|
||||||
|
.then(response => response.text())
|
||||||
|
.then(username => {
|
||||||
|
users[user] = username;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Discord Clone - Sign Up</title>
|
||||||
|
<link rel="stylesheet" href="static/css/index.css"/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="signup-container">
|
||||||
|
<div class="signup-header">
|
||||||
|
<div class="logo">DC</div>
|
||||||
|
<h1>Create Account</h1>
|
||||||
|
<p>Join the conversation today</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="signup-form">
|
||||||
|
<div class="success-message" id="successMessage">
|
||||||
|
Account created successfully! Redirecting...
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username">Username</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="username"
|
||||||
|
name="username"
|
||||||
|
placeholder="Enter your username"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="error-message">Username is required</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="email">Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
placeholder="Enter your email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="error-message">Please enter a valid email</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password">Password</label>
|
||||||
|
<div class="input-wrapper">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
placeholder="Enter your password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="password-toggle"
|
||||||
|
id="passwordToggle"
|
||||||
|
>
|
||||||
|
SHOW
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="error-message">
|
||||||
|
Password must be at least 8 characters
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="confirmPassword">Confirm Password</label>
|
||||||
|
<div class="input-wrapper">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="confirmPassword"
|
||||||
|
name="confirmPassword"
|
||||||
|
placeholder="Confirm your password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="password-toggle"
|
||||||
|
id="confirmPasswordToggle"
|
||||||
|
>
|
||||||
|
SHOW
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="error-message">Passwords do not match</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="checkbox-group">
|
||||||
|
<input type="checkbox" id="terms" name="terms" required />
|
||||||
|
<label for="terms">
|
||||||
|
I agree to the <a href="#">Terms of Service</a> and
|
||||||
|
<a href="#">Privacy Policy</a>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" class="submit-button" id="submitButton">
|
||||||
|
Create Account
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="signup-footer">
|
||||||
|
Already have an account? <a href="#">Log in</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const form = {
|
||||||
|
username: document.getElementById("username"),
|
||||||
|
email: document.getElementById("email"),
|
||||||
|
password: document.getElementById("password"),
|
||||||
|
confirmPassword: document.getElementById("confirmPassword"),
|
||||||
|
terms: document.getElementById("terms"),
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitButton = document.getElementById("submitButton");
|
||||||
|
const successMessage = document.getElementById("successMessage");
|
||||||
|
|
||||||
|
// Password toggle functionality
|
||||||
|
const passwordToggle = document.getElementById("passwordToggle");
|
||||||
|
const confirmPasswordToggle = document.getElementById(
|
||||||
|
"confirmPasswordToggle",
|
||||||
|
);
|
||||||
|
|
||||||
|
passwordToggle.addEventListener("click", function () {
|
||||||
|
const type =
|
||||||
|
form.password.type === "password" ? "text" : "password";
|
||||||
|
form.password.type = type;
|
||||||
|
this.textContent = type === "password" ? "SHOW" : "HIDE";
|
||||||
|
});
|
||||||
|
|
||||||
|
confirmPasswordToggle.addEventListener("click", function () {
|
||||||
|
const type =
|
||||||
|
form.confirmPassword.type === "password"
|
||||||
|
? "text"
|
||||||
|
: "password";
|
||||||
|
form.confirmPassword.type = type;
|
||||||
|
this.textContent = type === "password" ? "SHOW" : "HIDE";
|
||||||
|
});
|
||||||
|
|
||||||
|
// Validation functions
|
||||||
|
function validateUsername() {
|
||||||
|
const value = form.username.value.trim();
|
||||||
|
const isValid = value.length >= 3;
|
||||||
|
toggleError(form.username, !isValid);
|
||||||
|
return isValid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateEmail() {
|
||||||
|
const value = form.email.value.trim();
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
const isValid = emailRegex.test(value);
|
||||||
|
toggleError(form.email, !isValid);
|
||||||
|
return isValid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatePassword() {
|
||||||
|
const value = form.password.value;
|
||||||
|
const isValid = value.length >= 8;
|
||||||
|
toggleError(form.password, !isValid);
|
||||||
|
return isValid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateConfirmPassword() {
|
||||||
|
const isValid =
|
||||||
|
form.confirmPassword.value === form.password.value &&
|
||||||
|
form.confirmPassword.value.length > 0;
|
||||||
|
toggleError(form.confirmPassword, !isValid);
|
||||||
|
return isValid;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleError(input, hasError) {
|
||||||
|
const formGroup = input.closest(".form-group");
|
||||||
|
if (hasError) {
|
||||||
|
formGroup.classList.add("error");
|
||||||
|
} else {
|
||||||
|
formGroup.classList.remove("error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add blur validation
|
||||||
|
form.username.addEventListener("blur", validateUsername);
|
||||||
|
form.email.addEventListener("blur", validateEmail);
|
||||||
|
form.password.addEventListener("blur", validatePassword);
|
||||||
|
form.confirmPassword.addEventListener(
|
||||||
|
"blur",
|
||||||
|
validateConfirmPassword,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Form submission
|
||||||
|
submitButton.addEventListener("click", async function () {
|
||||||
|
// Validate all fields
|
||||||
|
const isUsernameValid = validateUsername();
|
||||||
|
const isEmailValid = validateEmail();
|
||||||
|
const isPasswordValid = validatePassword();
|
||||||
|
const isConfirmPasswordValid = validateConfirmPassword();
|
||||||
|
const areTermsAccepted = form.terms.checked;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!isUsernameValid ||
|
||||||
|
!isEmailValid ||
|
||||||
|
!isPasswordValid ||
|
||||||
|
!isConfirmPasswordValid ||
|
||||||
|
!areTermsAccepted
|
||||||
|
) {
|
||||||
|
if (!areTermsAccepted) {
|
||||||
|
alert("Please accept the Terms of Service");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disable button and show loading
|
||||||
|
submitButton.disabled = true;
|
||||||
|
submitButton.innerHTML =
|
||||||
|
'<span class="loading-spinner"></span>Creating Account...';
|
||||||
|
|
||||||
|
// Prepare data
|
||||||
|
const formData = {
|
||||||
|
username: form.username.value.trim(),
|
||||||
|
// email: form.email.value.trim(),
|
||||||
|
password: form.password.value,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Replace with your actual backend endpoint
|
||||||
|
const response = await fetch(
|
||||||
|
"http://localhost:8000/signup",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(formData),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// Show success message
|
||||||
|
successMessage.classList.add("show");
|
||||||
|
submitButton.innerHTML = "Account Created!";
|
||||||
|
|
||||||
|
// Optional: Redirect after success
|
||||||
|
setTimeout(() => {
|
||||||
|
// window.location.href = '/chat';
|
||||||
|
console.log("Redirecting to chat...");
|
||||||
|
}, 2000);
|
||||||
|
} else {
|
||||||
|
const error = await response.json();
|
||||||
|
throw new Error(error.message || "Signup failed");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Signup error:", error);
|
||||||
|
alert(
|
||||||
|
error.message ||
|
||||||
|
"Failed to create account. Please try again.",
|
||||||
|
);
|
||||||
|
submitButton.disabled = false;
|
||||||
|
submitButton.innerHTML = "Create Account";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Allow Enter key to submit
|
||||||
|
Object.values(form).forEach((input) => {
|
||||||
|
if (input.tagName === "INPUT") {
|
||||||
|
input.addEventListener("keypress", function (e) {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
submitButton.click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||