quoter/src/main.rs

135 lines
4.7 KiB
Rust
Raw Normal View History

2023-10-03 13:29:31 +00:00
use actix_web::{web, App, HttpResponse, HttpServer, web::Bytes};
2023-10-11 15:19:56 +00:00
use actix_web::middleware::Logger;
2023-10-02 09:22:04 +00:00
use redis::{Client, AsyncCommands};
2023-09-27 23:08:48 +00:00
use std::collections::HashMap;
use std::env;
2023-10-02 12:37:56 +00:00
use futures::StreamExt;
2023-10-03 10:43:21 +00:00
use tokio::sync::broadcast;
2023-10-03 13:29:31 +00:00
use actix_web::error::{ErrorUnauthorized, ErrorInternalServerError as ServerError};
2023-10-06 14:57:54 +00:00
use std::sync::{Arc, Mutex};
use tokio::task::JoinHandle;
2023-10-02 20:35:49 +00:00
2023-10-03 10:43:21 +00:00
mod data;
2023-10-02 13:47:22 +00:00
2023-10-06 14:57:54 +00:00
#[derive(Clone)]
struct AppState {
tasks: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
redis: Client,
}
async fn connect_handler(
2023-09-28 10:12:07 +00:00
token: web::Path<String>,
2023-10-06 14:57:54 +00:00
state: web::Data<AppState>,
2023-10-03 13:29:31 +00:00
) -> Result<HttpResponse, actix_web::Error> {
let listener_id = data::get_auth_id(&token).await.map_err(|e| {
eprintln!("TOKEN check failed: {}", e);
ErrorUnauthorized("Unauthorized")
})?;
2023-10-03 10:43:21 +00:00
2023-10-06 14:57:54 +00:00
let mut con = state.redis.get_async_connection().await.map_err(|e| {
2023-10-03 13:29:31 +00:00
eprintln!("Failed to get async connection: {}", e);
ServerError("Internal Server Error")
})?;
2023-10-02 18:55:10 +00:00
2023-10-03 13:29:31 +00:00
con.sadd::<&str, &i32, usize>("authors-online", &listener_id).await.map_err(|e| {
eprintln!("Failed to add author to online list: {}", e);
ServerError("Internal Server Error")
})?;
2023-10-02 09:22:04 +00:00
2023-10-03 13:29:31 +00:00
let chats: Vec<String> = con.smembers::<String, Vec<String>>(format!("chats_by_author/{}", listener_id)).await.map_err(|e| {
eprintln!("Failed to get chats by author: {}", e);
ServerError("Internal Server Error")
})?;
2023-09-28 10:12:07 +00:00
2023-10-03 10:43:21 +00:00
let (tx, mut rx) = broadcast::channel(100);
2023-10-06 15:07:24 +00:00
let state_clone = state.clone();
2023-10-06 14:57:54 +00:00
let handle = tokio::spawn(async move {
2023-10-06 15:07:24 +00:00
let conn = state_clone.redis.get_async_connection().await.unwrap();
2023-10-03 10:43:21 +00:00
let mut pubsub = conn.into_pubsub();
2023-09-28 10:12:07 +00:00
2023-10-03 13:29:31 +00:00
pubsub.subscribe("new_follower").await.unwrap();
2023-10-06 12:09:31 +00:00
println!("'new_follower' subscribed");
2023-10-03 13:29:31 +00:00
pubsub.subscribe("new_shout").await.unwrap();
2023-10-06 12:09:31 +00:00
println!("'new_shout' subscribed");
2023-10-03 13:29:31 +00:00
pubsub.subscribe("new_reaction").await.unwrap();
2023-10-06 12:09:31 +00:00
println!("'new_reaction' subscribed");
2023-10-03 13:29:31 +00:00
2023-10-03 10:43:21 +00:00
for chat_id in &chats {
let channel_name = format!("chat:{}", chat_id);
2023-10-03 13:29:31 +00:00
pubsub.subscribe(&channel_name).await.unwrap();
2023-10-06 12:10:17 +00:00
println!("'{}' subscribed", channel_name);
2023-10-03 05:02:11 +00:00
}
2023-10-03 10:43:21 +00:00
while let Some(msg) = pubsub.on_message().next().await {
2023-10-03 13:29:31 +00:00
let payload: HashMap<String, String> = msg.get_payload().unwrap();
if data::is_fitting(listener_id, payload.clone()).await.is_ok() {
let _ = tx.send(serde_json::to_string(&payload).unwrap());
};
2023-10-03 04:52:48 +00:00
}
2023-10-03 10:43:21 +00:00
});
2023-10-06 14:57:54 +00:00
state.tasks
.lock()
.unwrap()
.insert(format!("{}", listener_id.clone()), handle);
2023-10-03 04:52:48 +00:00
2023-10-03 13:29:31 +00:00
let server_event = rx.recv().await.map_err(|e| {
eprintln!("Failed to receive server event: {}", e);
ServerError("Internal Server Error")
})?;
2023-10-02 15:27:55 +00:00
let server_event_stream = futures::stream::once(async move { Ok::<_, actix_web::Error>(Bytes::from(server_event)) });
2023-10-03 13:29:31 +00:00
Ok(HttpResponse::Ok()
2023-10-02 11:24:45 +00:00
.append_header(("content-type", "text/event-stream"))
2023-10-03 13:29:31 +00:00
.streaming(server_event_stream))
2023-09-27 23:08:48 +00:00
}
2023-10-06 14:57:54 +00:00
async fn disconnect_handler(
token: web::Path<String>,
state: web::Data<AppState>,
) -> Result<HttpResponse, actix_web::Error> {
let listener_id = data::get_auth_id(&token).await.map_err(|e| {
eprintln!("TOKEN check failed: {}", e);
ErrorUnauthorized("Unauthorized")
})?;
if let Some(handle) = state.tasks.lock().unwrap().remove(&format!("{}", listener_id)) {
handle.abort();
let mut con = state.redis.get_async_connection().await.map_err(|e| {
eprintln!("Failed to get async connection: {}", e);
ServerError("Internal Server Error")
})?;
con.srem::<&str, &i32, usize>("authors-online", &listener_id).await.map_err(|e| {
eprintln!("Failed to remove author from online list: {}", e);
ServerError("Internal Server Error")
})?;
}
Ok(HttpResponse::Ok().finish())
}
2023-09-27 23:08:48 +00:00
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2023-10-03 13:29:31 +00:00
let redis_url = env::var("REDIS_URL").unwrap_or_else(|_| String::from("redis://127.0.0.1/"));
2023-10-06 12:10:54 +00:00
let client = redis::Client::open(redis_url.clone()).unwrap();
2023-10-06 14:57:54 +00:00
let tasks = Arc::new(Mutex::new(HashMap::new()));
let state = AppState {
tasks: tasks.clone(),
redis: client.clone(),
};
2023-10-11 15:02:49 +00:00
println!("Redis client initialized");
2023-09-27 23:08:48 +00:00
HttpServer::new(move || {
2023-10-11 15:02:49 +00:00
println!("Webserver initialized");
2023-09-27 23:08:48 +00:00
App::new()
2023-10-11 15:19:56 +00:00
.wrap(Logger::default()) // Added this line
2023-10-06 14:57:54 +00:00
.app_data(web::Data::new(state.clone()))
2023-10-11 15:08:12 +00:00
.service(
web::scope("")
.route("/", web::get().to(connect_handler))
)
2023-09-27 23:08:48 +00:00
})
2023-10-06 11:06:11 +00:00
.bind("127.0.0.1:8080")?
2023-09-27 23:08:48 +00:00
.run()
.await
2023-10-06 10:50:20 +00:00
}