String clean_chat_field(String raw, u32 max_length)
{
String value = trim(raw);
value = replace(value, "\r", " ");
value = replace(value, "\n", " ");
if(value.length() > max_length)
value.resize(max_length);
return(value);
}
DTree chat_event(String type, String body)
{
DTree event;
event["type"] = type;
event["body"] = body;
event["connection_id"] = ws_connection_id();
event["scope"] = first(context->params["DOCUMENT_URI"], ws_scope());
event["online"] = (f64)ws_connection_count();
event["at"] = gmdate("%H:%M:%S");
return(event);
}
RENDER()
{
String ws_url = context->params["DOCUMENT_URI"];
u64 online = ws_connection_count();
<>
>
}
WS()
{
DTree payload = json_decode(ws_message());
String type = clean_chat_field(payload["type"].to_string(), 24);
String name = clean_chat_field(payload["name"].to_string(), 32);
String body = clean_chat_field(payload["body"].to_string(), 500);
if(name == "")
name = "guest";
if(type == "join")
{
ws_send(json_encode(chat_event("join", name + " joined the room")));
return;
}
if(type == "message" && body != "")
{
DTree event = chat_event("message", body);
event["name"] = name;
ws_send(json_encode(event));
return;
}
if(type != "")
{
ws_send_to(ws_connection_id(), json_encode(chat_event("notice", "Unknown message type: " + type)));
}
}