quoter/src/main.rs

162 lines
4.6 KiB
Rust
Raw Normal View History

2023-10-02 09:22:04 +00:00
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use redis::{Client, AsyncCommands};
use reqwest::Client as HTTPClient;
use serde::{Serialize, Deserialize};
2023-09-28 10:12:07 +00:00
use serde_json::Value;
2023-09-27 23:08:48 +00:00
use std::collections::HashMap;
use std::env;
2023-10-02 10:16:57 +00:00
use std::error::Error;
2023-10-02 12:37:56 +00:00
use futures::StreamExt;
2023-10-02 09:22:04 +00:00
use tokio::sync::broadcast::{self, Receiver};
2023-10-02 13:55:31 +00:00
use uuid::Uuid;
use chrono::Utc;
2023-09-27 23:08:48 +00:00
2023-10-02 10:16:57 +00:00
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum PayloadKind {
NewMessage,
NewFollower,
NewShout,
NewApproval,
NewComment,
NewRate
}
2023-10-02 09:22:04 +00:00
#[derive(Debug, Serialize, Deserialize)]
2023-09-28 10:12:07 +00:00
struct Payload {
2023-10-02 09:22:04 +00:00
chat_id: Option<String>,
shout_id: Option<i32>,
2023-10-02 10:16:57 +00:00
author_id: Option<i32>,
topic_id: Option<i32>,
reaction_id: Option<i32>,
community_id: Option<i32>,
kind: PayloadKind,
body: String,
2023-09-27 23:08:48 +00:00
}
2023-10-02 10:16:57 +00:00
async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> {
2023-09-28 10:12:07 +00:00
let api_base = env::var("API_BASE")?;
2023-10-02 10:16:57 +00:00
let gql = match api_base.contains("v2") {
true => r#"mutation { getSession { user { id } } }"#, // v2
_ => r#"query { sessiom { user { id } } }"# // authorizer
2023-10-02 09:22:04 +00:00
};
let client = HTTPClient::new();
2023-09-28 10:12:07 +00:00
let response = client
.post(api_base)
2023-10-02 09:22:04 +00:00
.bearer_auth(token) // NOTE: auth token is here
2023-09-28 10:12:07 +00:00
.body(gql)
2023-09-27 23:08:48 +00:00
.send()
.await?;
2023-10-02 09:22:04 +00:00
let response_body: Value = response.json().await?;
2023-09-28 10:12:07 +00:00
let id = response_body["data"]["getSession"]["user"]["id"]
.as_i64()
.ok_or("Failed to get user id by token")? as i32;
Ok(id)
2023-09-27 23:08:48 +00:00
}
2023-10-02 13:47:22 +00:00
async fn create_first_chat(author_id: i32) -> Vec<String> {
2023-10-02 13:55:31 +00:00
let chat_id = Uuid::new_v4().to_string();
2023-10-02 13:47:22 +00:00
let members = vec![author_id.to_string(), "1".to_string()];
2023-10-02 13:55:31 +00:00
let timestamp = Utc::now().timestamp();
2023-10-02 13:47:22 +00:00
let chat = serde_json::json!({
"id": chat_id,
2023-10-02 13:55:31 +00:00
"admins": members,
"members": members.clone(),
"title": "",
"createdBy": author_id,
2023-10-02 13:47:22 +00:00
"createdAt": timestamp,
"updatedAt": timestamp,
});
let _: () = redis::pipe()
.atomic()
.sadd_multiple(format!("chats_by_author/{}", author_id), &members)
.set(format!("chats/{}", chat_id), chat.to_string())
.set(format!("chats/{}/next_message_id", chat_id), "0")
.query_async(&mut con)
.await
.unwrap();
vec![chat, ]
}
2023-09-28 10:12:07 +00:00
async fn sse_handler(
token: web::Path<String>,
2023-10-02 12:37:56 +00:00
mut rx: web::Data<Receiver<String>>,
2023-10-02 09:22:04 +00:00
redis: web::Data<Client>,
2023-09-28 10:12:07 +00:00
) -> impl Responder {
2023-10-02 10:16:57 +00:00
let author_id = match get_auth_id(&token).await {
2023-09-27 23:08:48 +00:00
Ok(id) => id,
Err(e) => {
2023-10-02 13:55:31 +00:00
eprintln!("TOKEN check failed: {}", e);
2023-10-02 09:22:04 +00:00
return HttpResponse::Unauthorized().finish();
2023-09-27 23:08:48 +00:00
}
};
2023-10-02 09:22:04 +00:00
let mut con = redis.get_async_connection().await.unwrap();
let _: () = con
.sadd("authors-online", &author_id)
.await
.unwrap();
2023-10-02 13:47:22 +00:00
let chats: Vec<String> = match con.smembers(format!("chats_by_author/{}", author_id)).await {
Ok(chats) => {
if chats.is_empty() {
create_first_chat(author_id).await
} else {
chats
}
},
Err(_) => create_first_chat(author_id).await
};
2023-09-28 10:12:07 +00:00
2023-10-02 09:22:04 +00:00
let mut pubsub = con.into_pubsub();
for chat_id in chats {
2023-10-02 13:47:22 +00:00
pubsub.subscribe(format!("chat:{}", chat_id)).await.unwrap();
2023-09-28 10:12:07 +00:00
}
2023-10-02 12:30:53 +00:00
let server_event = rx.recv().await.unwrap();
2023-10-02 09:22:04 +00:00
let _: () = con
.srem("authors-online", &author_id)
.await
.unwrap();
HttpResponse::Ok()
2023-10-02 11:24:45 +00:00
.append_header(("content-type", "text/event-stream"))
2023-10-02 09:22:04 +00:00
.streaming(server_event)
2023-09-27 23:08:48 +00:00
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
2023-10-02 12:37:56 +00:00
let (tx, _rx) = broadcast::channel(100);
2023-09-28 10:12:07 +00:00
let redis_url = env::var("REDIS_URL").unwrap();
2023-10-02 09:22:04 +00:00
let client = redis::Client::open(redis_url).unwrap();
2023-09-28 10:12:07 +00:00
let _handle = tokio::spawn(async move {
let mut conn = client.get_async_connection().await.unwrap();
let mut pubsub = conn.into_pubsub();
pubsub.subscribe("new_follower").await.unwrap();
pubsub.subscribe("new_shout").await.unwrap();
2023-10-02 09:22:04 +00:00
pubsub.subscribe("new_reaction").await.unwrap();
2023-09-28 10:12:07 +00:00
2023-10-02 12:30:53 +00:00
while let Some(msg) = pubsub.on_message().next().await {
2023-09-28 10:12:07 +00:00
let payload: HashMap<String, String> = msg.get_payload().unwrap();
tx.send(serde_json::to_string(&payload).unwrap()).unwrap();
}
});
2023-09-27 23:08:48 +00:00
HttpServer::new(move || {
2023-10-02 12:35:16 +00:00
let rx = tx.subscribe();
2023-09-27 23:08:48 +00:00
App::new()
2023-10-02 12:35:16 +00:00
.app_data(web::Data::new(rx))
2023-10-02 11:48:27 +00:00
.app_data(web::Data::new(client.clone()))
2023-10-02 09:22:04 +00:00
.route("/aware/{token}", web::get().to(sse_handler))
2023-09-27 23:08:48 +00:00
})
.bind("127.0.0.1:8080")?
.run()
.await
}