1 Commits

Author SHA1 Message Date
maurice
13870d48a1 hallo toegevoegd 2025-11-03 08:19:47 +01:00
2 changed files with 7 additions and 43 deletions

View File

@@ -1,16 +1,17 @@
use std::{collections::HashMap, env, fs::{self, File}, sync::{Arc, Mutex}, thread}; use std::{env, fs::{self, File}, thread};
use chrono::Utc; use chrono::Utc;
use kv::{Config, Store, Json, Bucket, Value}; use kv::{Config, Store, Json, Bucket, Value};
use paste::Paste; use paste::Paste;
use rand::{Rng, distributions::Alphanumeric}; use rand::{Rng, distributions::Alphanumeric};
use rouille::{post_input, router, try_or_400, websocket, Request, Response, Server}; use rouille::{Response, router, try_or_400, post_input, Request, Server};
use signal_hook::{iterator::Signals, consts::{SIGINT, SIGTERM}}; use signal_hook::{iterator::Signals, consts::{SIGINT, SIGTERM}};
mod paste; mod paste;
// Generate random key function // Generate random key function
fn random_string() -> String { fn random_string() -> String {
// hallo
rand::thread_rng() rand::thread_rng()
.sample_iter(&Alphanumeric) .sample_iter(&Alphanumeric)
.take(5) .take(5)
@@ -30,7 +31,6 @@ fn generate_key<T : Value>(key: Option<String>, store: &Bucket<String, T>) -> St
} }
} }
// Get query parameters
fn get_query(req: &Request, name: &str) -> Option<String> { fn get_query(req: &Request, name: &str) -> Option<String> {
let params: Vec<&str> = req.raw_query_string().split('&').collect(); let params: Vec<&str> = req.raw_query_string().split('&').collect();
let param = params.iter().find(|p|p.starts_with(&format!("{}=", name))); let param = params.iter().find(|p|p.starts_with(&format!("{}=", name)));
@@ -59,8 +59,6 @@ fn main() {
let links = store.bucket::<String, String>(Some("links")) let links = store.bucket::<String, String>(Some("links"))
.expect("Failed to open links bucket"); .expect("Failed to open links bucket");
// Temp pastes
let temp_pastes = Arc::new(Mutex::new(HashMap::new()));
// Create server // Create server
let server = Server::new(format!("0.0.0.0:{}", port), move |req| { let server = Server::new(format!("0.0.0.0:{}", port), move |req| {
@@ -71,10 +69,6 @@ fn main() {
} }
} }
if req.url().starts_with("/ws") {
handle_websocket(temp_pastes.clone(), &req);
}
router!(req, router!(req,
(GET) (/) => { (GET) (/) => {
match File::open(format!("{}/index.html", &source_dir)) { match File::open(format!("{}/index.html", &source_dir)) {
@@ -122,7 +116,7 @@ fn main() {
}, },
(POST) (/{id: String}) => { (POST) (/{id: String}) => {
let id = if id.is_empty() { None } else { Some(id) }; let id = if id.is_empty() { None } else { Some(id) };
register_paste(&pastes, req, id, prefix.clone(), None) register_paste(&pastes, req, id, prefix.clone())
}, },
_ => Response::empty_404() _ => Response::empty_404()
) )
@@ -150,7 +144,8 @@ fn main() {
} }
// Register paste handler // Register paste handler
fn register_paste(pastes: &Bucket<String, Json<Paste>>, req: &Request, id: Option<String>, prefix: Option<String>, allow_edit: Option<bool>) -> Response { fn register_paste(pastes: &Bucket<String, Json<Paste>>, req: &Request, id: Option<String>, prefix: Option<String>) -> Response {
// Try read body from form data, and if not present from request body // Try read body from form data, and if not present from request body
let body = match post_input!(req, { let body = match post_input!(req, {
content: String content: String
@@ -171,7 +166,6 @@ fn register_paste(pastes: &Bucket<String, Json<Paste>>, req: &Request, id: Optio
content: body, content: body,
expires: None, expires: None,
language, language,
allow_edit,
created: Utc::now() created: Utc::now()
}); });
@@ -216,32 +210,4 @@ fn register_link(links: &Bucket<String,String>, req: &Request, id: Option<String
}; };
Response::text(url) Response::text(url)
}
fn handle_websocket(pastes: Arc<Mutex<HashMap<String, String>>>, req: &Request) -> Response {
let key = get_query(&req, "key").unwrap();
let mut current_text = String::new();
match pastes.lock().expect("Failed to access pastes DB").get(&key) {
Some(paste) => {
current_text = paste.clone()
},
None => {
// OK, ignore
}
}
let (response, websocket) = try_or_400!(websocket::start(req, Some("pastabble")));
if let Ok(mut ws) = websocket.recv() {
thread::spawn(move || {
if !current_text.is_empty() {
_ = ws.send_text(&current_text);
}
});
return response.with_additional_header("Access-Control-Allow-Origin", "*");
} else {
return Response::empty_400()
}
} }

View File

@@ -9,7 +9,5 @@ pub struct Paste {
#[serde(with = "ts_seconds_option")] #[serde(with = "ts_seconds_option")]
pub expires: Option<DateTime<Utc>>, pub expires: Option<DateTime<Utc>>,
pub created: DateTime<Utc>, pub created: DateTime<Utc>
pub allow_edit: Option<bool>
} }