updated fully featured text messaging
This commit is contained in:
1 parent
d9d3dd2de9
commit
ded35ae796
4 files changed
+1926
-163
No files matched your search
+203
-8
@@ -1,7 +1,7 @@
|
||||
use axum::{
|
||||
extract::{
|
||||
ws::{Message, WebSocket, WebSocketUpgrade},
|
||||
State, Json, Query,
|
||||
State, Json, Query, Multipart,
|
||||
},
|
||||
response::Response,
|
||||
routing::{get, post, delete},
|
||||
@@ -13,6 +13,7 @@ use std::{
|
||||
collections::HashMap,
|
||||
net::SocketAddr,
|
||||
sync::Arc,
|
||||
path::Path,
|
||||
};
|
||||
use tokio::sync::{mpsc, RwLock};
|
||||
use tower_http::services::ServeDir;
|
||||
@@ -21,6 +22,8 @@ use bcrypt::{hash, verify, DEFAULT_COST};
|
||||
use rand::distributions::Alphanumeric;
|
||||
use rand::{thread_rng, Rng};
|
||||
use chrono::{Utc, Duration};
|
||||
use uuid::Uuid;
|
||||
use std::io::Cursor;
|
||||
|
||||
// Types for shared state
|
||||
type UserMap = Arc<RwLock<HashMap<String, mpsc::UnboundedSender<Message>>>>;
|
||||
@@ -72,6 +75,7 @@ struct AuthResponse {
|
||||
struct UserProfile {
|
||||
username: String,
|
||||
phone: String,
|
||||
avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -79,6 +83,7 @@ struct ValidateTokenResponse {
|
||||
success: bool,
|
||||
username: Option<String>,
|
||||
phone: Option<String>,
|
||||
avatar_url: Option<String>,
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
@@ -86,6 +91,7 @@ struct ValidateTokenResponse {
|
||||
struct ChatPartner {
|
||||
username: String,
|
||||
phone: String,
|
||||
avatar_url: Option<String>,
|
||||
last_message: Option<String>,
|
||||
last_message_time: Option<i64>,
|
||||
unread_count: i64,
|
||||
@@ -114,11 +120,21 @@ struct DeleteMessageResponse {
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct UploadAvatarResponse {
|
||||
success: bool,
|
||||
avatar_url: Option<String>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Initialize logging
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Create avatars directory if it doesn't exist
|
||||
tokio::fs::create_dir_all("web/avatars").await?;
|
||||
|
||||
// Initialize database
|
||||
let db_pool = init_db().await?;
|
||||
|
||||
@@ -139,6 +155,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.route("/api/debug-messages", get(debug_messages_handler))
|
||||
.route("/api/mark-read", post(mark_read_handler))
|
||||
.route("/api/delete-message", post(delete_message_handler))
|
||||
.route("/api/upload-avatar", post(upload_avatar_handler))
|
||||
.route("/api/profile", get(profile_handler))
|
||||
.nest_service("/", ServeDir::new("web"))
|
||||
.with_state(state);
|
||||
@@ -163,6 +180,7 @@ async fn init_db() -> Result<SqlitePool, Box<dyn std::error::Error>> {
|
||||
phone TEXT UNIQUE NOT NULL,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
avatar_url TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"#,
|
||||
@@ -391,7 +409,7 @@ async fn validate_token_handler(
|
||||
Ok(Some(username)) => {
|
||||
// Get user details
|
||||
let user_result = sqlx::query(
|
||||
"SELECT phone FROM users WHERE username = ?"
|
||||
"SELECT phone, avatar_url FROM users WHERE username = ?"
|
||||
)
|
||||
.bind(&username)
|
||||
.fetch_optional(&state.db_pool)
|
||||
@@ -400,10 +418,12 @@ async fn validate_token_handler(
|
||||
match user_result {
|
||||
Ok(Some(row)) => {
|
||||
let phone: String = row.get("phone");
|
||||
let avatar_url: Option<String> = row.get("avatar_url");
|
||||
Json(ValidateTokenResponse {
|
||||
success: true,
|
||||
username: Some(username),
|
||||
phone: Some(phone),
|
||||
avatar_url,
|
||||
message: None,
|
||||
})
|
||||
}
|
||||
@@ -411,12 +431,14 @@ async fn validate_token_handler(
|
||||
success: false,
|
||||
username: None,
|
||||
phone: None,
|
||||
avatar_url: None,
|
||||
message: Some("User not found".to_string()),
|
||||
}),
|
||||
Err(_) => Json(ValidateTokenResponse {
|
||||
success: false,
|
||||
username: None,
|
||||
phone: None,
|
||||
avatar_url: None,
|
||||
message: Some("Database error".to_string()),
|
||||
}),
|
||||
}
|
||||
@@ -425,12 +447,14 @@ async fn validate_token_handler(
|
||||
success: false,
|
||||
username: None,
|
||||
phone: None,
|
||||
avatar_url: None,
|
||||
message: Some("Invalid or expired token".to_string()),
|
||||
}),
|
||||
Err(_) => Json(ValidateTokenResponse {
|
||||
success: false,
|
||||
username: None,
|
||||
phone: None,
|
||||
avatar_url: None,
|
||||
message: Some("Token verification error".to_string()),
|
||||
}),
|
||||
}
|
||||
@@ -615,7 +639,7 @@ async fn get_chats_handler(
|
||||
|
||||
// Получаем информацию о пользователе
|
||||
let user_result = sqlx::query(
|
||||
"SELECT username, phone FROM users WHERE username = ?"
|
||||
"SELECT username, phone, avatar_url FROM users WHERE username = ?"
|
||||
)
|
||||
.bind(&partner_username)
|
||||
.fetch_optional(&state.db_pool)
|
||||
@@ -625,6 +649,7 @@ async fn get_chats_handler(
|
||||
Ok(Some(user_row)) => {
|
||||
let partner_name: String = user_row.get("username");
|
||||
let phone: String = user_row.get("phone");
|
||||
let avatar_url: Option<String> = user_row.get("avatar_url");
|
||||
|
||||
// Получаем последнее сообщение
|
||||
let last_message_result = sqlx::query(
|
||||
@@ -684,6 +709,7 @@ async fn get_chats_handler(
|
||||
let chat = ChatPartner {
|
||||
username: partner_name.clone(),
|
||||
phone,
|
||||
avatar_url,
|
||||
last_message,
|
||||
last_message_time,
|
||||
unread_count,
|
||||
@@ -738,7 +764,7 @@ async fn search_users_handler(
|
||||
|
||||
let users = sqlx::query(
|
||||
r#"
|
||||
SELECT username, phone
|
||||
SELECT username, phone, avatar_url
|
||||
FROM users
|
||||
WHERE (username LIKE ? OR phone LIKE ?)
|
||||
AND username != ?
|
||||
@@ -758,6 +784,7 @@ async fn search_users_handler(
|
||||
results.push(ChatPartner {
|
||||
username: row.get("username"),
|
||||
phone: row.get("phone"),
|
||||
avatar_url: row.get("avatar_url"),
|
||||
last_message: None,
|
||||
last_message_time: None,
|
||||
unread_count: 0,
|
||||
@@ -939,13 +966,181 @@ async fn delete_message_handler(
|
||||
}
|
||||
}
|
||||
|
||||
async fn profile_handler() -> Json<UserProfile> {
|
||||
Json(UserProfile {
|
||||
username: "user".to_string(),
|
||||
phone: "+1234567890".to_string(),
|
||||
// Upload avatar endpoint
|
||||
async fn upload_avatar_handler(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
mut multipart: Multipart,
|
||||
) -> Json<UploadAvatarResponse> {
|
||||
// Extract token from header
|
||||
let token = if let Some(auth_header) = headers.get("authorization") {
|
||||
auth_header.to_str().unwrap_or("").replace("Bearer ", "")
|
||||
} else {
|
||||
return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "No token".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
// Get current user from token
|
||||
let username = match verify_token(&state.db_pool, &token).await {
|
||||
Ok(Some(user)) => user,
|
||||
_ => return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "Invalid token".to_string(),
|
||||
}),
|
||||
};
|
||||
|
||||
// Process multipart form
|
||||
while let Some(field) = multipart.next_field().await.unwrap() {
|
||||
let field_name = field.name().unwrap_or("").to_string();
|
||||
|
||||
if field_name == "avatar" {
|
||||
let data = field.bytes().await.unwrap();
|
||||
|
||||
// Validate image size (max 5MB)
|
||||
if data.len() > 5 * 1024 * 1024 {
|
||||
return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "Image too large (max 5MB)".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
// Process image
|
||||
match process_avatar(&data).await {
|
||||
Ok(processed_data) => {
|
||||
// Generate unique filename
|
||||
let filename = format!("{}.jpg", Uuid::new_v4());
|
||||
let avatar_path = format!("web/avatars/{}", filename);
|
||||
|
||||
// Save file
|
||||
if let Err(e) = tokio::fs::write(&avatar_path, &processed_data).await {
|
||||
eprintln!("Error saving avatar: {}", e);
|
||||
return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "Error saving image".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let avatar_url = format!("/avatars/{}", filename);
|
||||
|
||||
// Update user in database
|
||||
let result = sqlx::query(
|
||||
"UPDATE users SET avatar_url = ? WHERE username = ?"
|
||||
)
|
||||
.bind(&avatar_url)
|
||||
.bind(&username)
|
||||
.execute(&state.db_pool)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
return Json(UploadAvatarResponse {
|
||||
success: true,
|
||||
avatar_url: Some(avatar_url),
|
||||
message: "Avatar uploaded successfully".to_string(),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error updating user avatar: {}", e);
|
||||
return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "Database error".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
return Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Json(UploadAvatarResponse {
|
||||
success: false,
|
||||
avatar_url: None,
|
||||
message: "No avatar file provided".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
// Process and resize avatar
|
||||
async fn process_avatar(data: &[u8]) -> Result<Vec<u8>, String> {
|
||||
// Load image
|
||||
let img = match image::load_from_memory(data) {
|
||||
Ok(img) => img,
|
||||
Err(_) => return Err("Invalid image format".to_string()),
|
||||
};
|
||||
|
||||
// Resize image to 150x150 pixels
|
||||
let resized = img.resize_to_fill(150, 150, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
// Convert to JPEG
|
||||
let mut jpeg_data = Vec::new();
|
||||
match resized.write_to(&mut Cursor::new(&mut jpeg_data), image::ImageFormat::Jpeg) {
|
||||
Ok(_) => Ok(jpeg_data),
|
||||
Err(_) => Err("Error processing image".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn profile_handler(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: axum::http::HeaderMap,
|
||||
) -> Json<UserProfile> {
|
||||
// Extract token from header
|
||||
let token = if let Some(auth_header) = headers.get("authorization") {
|
||||
auth_header.to_str().unwrap_or("").replace("Bearer ", "")
|
||||
} else {
|
||||
return Json(UserProfile {
|
||||
username: "user".to_string(),
|
||||
phone: "+1234567890".to_string(),
|
||||
avatar_url: None,
|
||||
});
|
||||
};
|
||||
|
||||
// Get current user from token
|
||||
let username = match verify_token(&state.db_pool, &token).await {
|
||||
Ok(Some(user)) => user,
|
||||
_ => return Json(UserProfile {
|
||||
username: "user".to_string(),
|
||||
phone: "+1234567890".to_string(),
|
||||
avatar_url: None,
|
||||
}),
|
||||
};
|
||||
|
||||
// Get user details
|
||||
let user_result = sqlx::query(
|
||||
"SELECT username, phone, avatar_url FROM users WHERE username = ?"
|
||||
)
|
||||
.bind(&username)
|
||||
.fetch_optional(&state.db_pool)
|
||||
.await;
|
||||
|
||||
match user_result {
|
||||
Ok(Some(row)) => {
|
||||
Json(UserProfile {
|
||||
username: row.get("username"),
|
||||
phone: row.get("phone"),
|
||||
avatar_url: row.get("avatar_url"),
|
||||
})
|
||||
}
|
||||
_ => Json(UserProfile {
|
||||
username: "user".to_string(),
|
||||
phone: "+1234567890".to_string(),
|
||||
avatar_url: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// WebSocket handlers
|
||||
async fn websocket_handler(
|
||||
ws: WebSocketUpgrade,
|
||||
|
||||
Reference in new issue
Block a user