2015-04-05 14:59:21 -07:00
|
|
|
state = "authenticating";
|
|
|
|
|
|
|
|
function authenticate(event) {
|
|
|
|
$("#alert").hide();
|
|
|
|
websocket.send(JSON.stringify({name: $("#username").val() }));
|
|
|
|
}
|
|
|
|
|
2015-04-05 22:42:47 -07:00
|
|
|
function send(event) {
|
|
|
|
websocket.send("\"" + $("#uinput").val() + "\"\n");
|
|
|
|
$("#uinput").val("");
|
|
|
|
}
|
|
|
|
|
2015-04-05 14:59:21 -07:00
|
|
|
$(function(){
|
|
|
|
$("#auth").hide();
|
|
|
|
$("#alert").hide();
|
|
|
|
$("#stream").hide();
|
2015-04-05 22:42:47 -07:00
|
|
|
$("#uinputs").hide();
|
2015-04-05 14:59:21 -07:00
|
|
|
$("#submit-username").click(authenticate);
|
2015-08-25 21:26:01 -07:00
|
|
|
$('#username').keydown(function (e){
|
|
|
|
if(e.keyCode == 13 || e.keyCode == 32){
|
|
|
|
authenticate();
|
|
|
|
}
|
|
|
|
})
|
2015-04-05 22:42:47 -07:00
|
|
|
$("#submit-uinput").click(send);
|
2015-04-05 14:59:21 -07:00
|
|
|
setupWS();
|
|
|
|
});
|
|
|
|
|
|
|
|
function setupWS() {
|
|
|
|
a = document.createElement("a");
|
|
|
|
a.href = document.URL;
|
|
|
|
url = "ws://" + a.hostname + ":8000/ws/";
|
|
|
|
websocket = new WebSocket(url);
|
|
|
|
websocket.onopen = function(evt) { onOpen(evt) };
|
|
|
|
websocket.onclose = function(evt) { onClose(evt) };
|
|
|
|
websocket.onmessage = function(evt) { onMessage(evt) };
|
|
|
|
websocket.onerror = function(evt) { onError(evt) };
|
|
|
|
}
|
|
|
|
|
|
|
|
function onOpen(e) {
|
|
|
|
console.log("websocket opened");
|
|
|
|
$("#auth").show();
|
|
|
|
}
|
|
|
|
|
|
|
|
function onClose(e) {
|
|
|
|
console.error("websocket disconnected");
|
2015-04-05 22:42:47 -07:00
|
|
|
$("#alert").show().text("client disconnect; please reload page");
|
|
|
|
$("#stream, #auth").hide();
|
2015-04-05 14:59:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
function onMessage(e) {
|
|
|
|
var payload = JSON.parse(e.data);
|
|
|
|
if (state === "authenticating") {
|
|
|
|
if (!payload.success) {
|
|
|
|
console.error(payload);
|
|
|
|
$("#alert").show().text(payload.error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
$("#auth").hide();
|
|
|
|
$("#stream").show();
|
2015-04-05 22:42:47 -07:00
|
|
|
$("#uinputs").show();
|
|
|
|
$(':input').keydown(function (e){
|
|
|
|
if(e.keyCode == 13){
|
|
|
|
send();
|
|
|
|
}
|
|
|
|
})
|
2015-04-05 14:59:21 -07:00
|
|
|
state = "chatting";
|
|
|
|
} else if (state === "chatting") {
|
2015-04-05 22:42:47 -07:00
|
|
|
var msg = $("#msg").clone();
|
|
|
|
msg.text(payload);
|
|
|
|
$("#chatter").prepend(msg.show());
|
|
|
|
var s = $("#chatter").children().size();
|
|
|
|
if (s > 20) {
|
|
|
|
var s = $("#chatter").children().last().remove();
|
|
|
|
}
|
2015-04-05 14:59:21 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function onError(e) {
|
|
|
|
console.error("websocket connection failure: " + JSON.stringify(e));
|
|
|
|
}
|
|
|
|
|
|
|
|
function negociate() {
|
|
|
|
var payload = {name: $("#username").val()};
|
|
|
|
websocket.send(JSON.stringify(payload));
|
|
|
|
}
|