From 15230facd5af9c97364a49d2d65eeca224fe8831 Mon Sep 17 00:00:00 2001 From: Kay Faraday Date: Thu, 5 May 2022 05:40:45 +0000 Subject: [PATCH] use nanoid instead of UUID --- Cargo.lock | 20 +++++++++--------- Cargo.toml | 2 +- frontend/index.html | 2 +- frontend/lib/join-session.mjs | 2 +- src/main.rs | 38 +++++++++++++++-------------------- src/viewer_connection.rs | 31 ++++++++++++++-------------- src/watch_session.rs | 11 +++++----- 7 files changed, 49 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0dde8c7..2a0aab7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -477,6 +477,15 @@ dependencies = [ "twoway", ] +[[package]] +name = "nanoid" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" +dependencies = [ + "rand 0.8.4", +] + [[package]] name = "ntapi" version = "0.3.6" @@ -1047,15 +1056,6 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" -[[package]] -name = "uuid" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" -dependencies = [ - "getrandom 0.2.3", -] - [[package]] name = "version_check" version = "0.9.3" @@ -1119,12 +1119,12 @@ version = "0.1.0" dependencies = [ "futures", "futures-util", + "nanoid", "once_cell", "serde", "serde_json", "tokio", "tokio-stream", - "uuid", "warp", ] diff --git a/Cargo.toml b/Cargo.toml index 8a57317..611c036 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,5 +11,5 @@ serde = { version = "1.0.130", features = ["derive"] } serde_json = "1.0.68" tokio = { version = "1.12.0", features = ["full"] } tokio-stream = { version = "0.1.7", features = ["fs"] } -uuid = { version = "0.8.2", features = ["v4"] } warp = "0.3.1" +nanoid = "0.4.0" \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html index 8ff978d..44eaf2d 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -39,7 +39,7 @@ diff --git a/frontend/lib/join-session.mjs b/frontend/lib/join-session.mjs index a33fdba..4cc0f44 100644 --- a/frontend/lib/join-session.mjs +++ b/frontend/lib/join-session.mjs @@ -69,7 +69,7 @@ export const setupJoinSessionForm = () => { loadNickname(nickname); loadColour(colour); - if (window.location.hash.match(/#[0-9a-f\-]+/)) { + if (window.location.hash.match(/#[A-Za-z0-9_\-]+/)) { sessionId.value = window.location.hash.substring(1); } diff --git a/src/main.rs b/src/main.rs index 9d29e35..e458613 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ use serde_json::json; use std::net::IpAddr; -use uuid::Uuid; use warb::{hyper::StatusCode, Filter, Reply}; use warp as warb; // i think it's funny +use nanoid::nanoid; + mod events; mod utils; mod viewer_connection; @@ -54,39 +55,32 @@ async fn main() { .and(warb::body::json()) .map(|body: StartSessionBody| { let mut sessions = SESSIONS.lock().unwrap(); - let session_uuid = Uuid::new_v4(); + let session_id = nanoid!(12); let session = WatchSession::new(body.video_url, body.subtitle_tracks); let session_view = session.view(); - sessions.insert(session_uuid, session); + sessions.insert(session_id.clone(), session); - warb::reply::json(&json!({ "id": session_uuid.to_string(), "session": session_view })) + warb::reply::json(&json!({ "id": session_id.to_string(), "session": session_view })) }); let get_emoji_route = warb::path!("emojos").and_then(get_emoji_list); enum RequestedSession { - Session(Uuid, WatchSession), + Session(String, WatchSession), Error(warb::reply::WithStatus), } let get_running_session = warb::path::path("sess") .and(warb::path::param::()) .map(|session_id: String| { - if let Ok(uuid) = Uuid::parse_str(&session_id) { - get_session(uuid) - .map(|sess| RequestedSession::Session(uuid, sess)) - .unwrap_or_else(|| { - RequestedSession::Error(warb::reply::with_status( - warb::reply::json(&json!({ "error": "session does not exist" })), - StatusCode::NOT_FOUND, - )) - }) - } else { - RequestedSession::Error(warb::reply::with_status( - warb::reply::json(&json!({ "error": "invalid session UUID" })), - StatusCode::BAD_REQUEST, - )) - } + get_session(&session_id) + .map(|sess| RequestedSession::Session(session_id, sess)) + .unwrap_or_else(|| { + RequestedSession::Error(warb::reply::with_status( + warb::reply::json(&json!({ "error": "session does not exist" })), + StatusCode::NOT_FOUND, + )) + }) }); let get_status_route = get_running_session @@ -104,8 +98,8 @@ async fn main() { .and(warb::ws()) .map( |requested_session, query: SubscribeQuery, ws: warb::ws::Ws| match requested_session { - RequestedSession::Session(uuid, _) => ws - .on_upgrade(move |ws| ws_subscribe(uuid, query.nickname, query.colour, ws)) + RequestedSession::Session(session_id, _) => ws + .on_upgrade(move |ws| ws_subscribe(session_id, query.nickname, query.colour, ws)) .into_response(), RequestedSession::Error(error_response) => error_response.into_response(), }, diff --git a/src/viewer_connection.rs b/src/viewer_connection.rs index ea38161..e16a636 100644 --- a/src/viewer_connection.rs +++ b/src/viewer_connection.rs @@ -11,7 +11,6 @@ use tokio::sync::{ }; use tokio_stream::wrappers::UnboundedReceiverStream; -use uuid::Uuid; use warp::ws::{Message, WebSocket}; use crate::{ @@ -25,14 +24,14 @@ static CONNECTED_VIEWERS: Lazy>> = static NEXT_VIEWER_ID: AtomicUsize = AtomicUsize::new(1); pub struct ConnectedViewer { - pub session: Uuid, + pub session: String, pub viewer_id: usize, pub tx: UnboundedSender, pub nickname: Option, pub colour: Option, } -pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, ws: WebSocket) { +pub async fn ws_subscribe(session_id: String, nickname: String, colour: String, ws: WebSocket) { let viewer_id = NEXT_VIEWER_ID.fetch_add(1, Ordering::Relaxed); let (mut viewer_ws_tx, mut viewer_ws_rx) = ws.split(); @@ -60,7 +59,7 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, viewer_id, ConnectedViewer { viewer_id, - session: session_uuid, + session: session_id.to_string(), tx, nickname: Some(nickname.clone()), colour: Some(colour.clone()), @@ -68,13 +67,13 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, ); ws_publish( - session_uuid, + &session_id, None, WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserJoin), ) .await; - update_viewer_list(session_uuid).await; + update_viewer_list(&session_id).await; while let Some(Ok(message)) = viewer_ws_rx.next().await { let event: WatchEventData = match message @@ -86,7 +85,7 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, None => continue, }; - let session = &mut get_session(session_uuid).unwrap(); + let session = &mut get_session(&session_id).unwrap(); // server side event modification where neccessary let event: WatchEventData = match event { @@ -97,10 +96,10 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, _ => event, }; - handle_watch_event_data(session_uuid, session, event.clone()); + handle_watch_event_data(&session_id, session, event.clone()); ws_publish( - session_uuid, + &session_id, Some(viewer_id), WatchEvent::new(nickname.clone(), colour.clone(), event), ) @@ -108,19 +107,19 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, } ws_publish( - session_uuid, + &session_id, None, WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserLeave), ) .await; CONNECTED_VIEWERS.write().await.remove(&viewer_id); - update_viewer_list(session_uuid).await; + update_viewer_list(&session_id).await; } -pub async fn ws_publish(session_uuid: Uuid, skip_viewer_id: Option, event: WatchEvent) { +pub async fn ws_publish(session_id: &str, skip_viewer_id: Option, event: WatchEvent) { for viewer in CONNECTED_VIEWERS.read().await.values() { - if viewer.session != session_uuid { + if viewer.session != session_id { continue; } @@ -131,11 +130,11 @@ pub async fn ws_publish(session_uuid: Uuid, skip_viewer_id: Option, event } } -async fn update_viewer_list(session_uuid: Uuid) { +async fn update_viewer_list(session_id: &str) { let mut viewers = Vec::new(); for viewer in CONNECTED_VIEWERS.read().await.values() { - if viewer.session == session_uuid { + if viewer.session == session_id { viewers.push(Viewer { nickname: viewer.nickname.clone(), colour: viewer.colour.clone(), @@ -144,7 +143,7 @@ async fn update_viewer_list(session_uuid: Uuid) { } ws_publish( - session_uuid, + &session_id, None, WatchEvent::new( String::from("server"), diff --git a/src/watch_session.rs b/src/watch_session.rs index cda42c5..15cf3a7 100644 --- a/src/watch_session.rs +++ b/src/watch_session.rs @@ -1,7 +1,6 @@ use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Mutex, time::Instant}; -use uuid::Uuid; use crate::events::WatchEventData; @@ -68,15 +67,15 @@ impl WatchSession { } } -pub static SESSIONS: Lazy>> = +pub static SESSIONS: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); -pub fn get_session(uuid: Uuid) -> Option { - SESSIONS.lock().unwrap().get(&uuid).cloned() +pub fn get_session(id: &str) -> Option { + SESSIONS.lock().unwrap().get(id).cloned() } pub fn handle_watch_event_data( - uuid: Uuid, + id: &str, watch_session: &mut WatchSession, event: WatchEventData, ) { @@ -92,5 +91,5 @@ pub fn handle_watch_event_data( _ => {} }; - let _ = SESSIONS.lock().unwrap().insert(uuid, watch_session.clone()); + let _ = SESSIONS.lock().unwrap().insert(id.to_string(), watch_session.clone()); }