jam-cloud/web/app/assets/javascripts/jamsocket.js

66 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2012-09-03 22:03:16 +00:00
// defines session-centric websocket code
2012-12-07 00:44:08 +00:00
(function(context, $) {
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
"use strict";
var jamsocket = {};
2012-09-03 22:03:16 +00:00
function debug_print(msg, inner) {
2012-12-07 00:44:08 +00:00
var msg_div = $("<div style='margin-top:20px; border-width:0 0 1px; border-color:#ccc; border-style:solid'>");
var msg_header = $("<h4 style='margin-bottom:2px'>").text(msg.type);
msg_div.append(msg_header);
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
var list = $("<dl style='margin-left:20px; margin-top:0'>");
msg_div.append(list);
2012-09-03 22:03:16 +00:00
for (var key in inner) {
2012-12-07 00:44:08 +00:00
list.append($("<dt>").text(key));
list.append($("<dd>").text(inner[key]));
2012-09-03 22:03:16 +00:00
}
2012-12-07 00:44:08 +00:00
$("#internal_session_activity").append(msg_div);
2012-09-03 22:03:16 +00:00
}
jamsocket.init = function() {
function send(msg) {
2012-12-07 00:44:08 +00:00
ws.send(context.JSON.stringify(msg));
2012-09-03 22:03:16 +00:00
}
// Let the library know where WebSocketMain.swf is:
2012-12-07 00:44:08 +00:00
context.WEB_SOCKET_SWF_LOCATION = "assets/flash/WebSocketMain.swf";
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
var mf = context.message_factory;
2012-09-03 22:03:16 +00:00
// Write your code in the same way as for native WebSocket:
2012-12-07 00:44:08 +00:00
var ws = new context.WebSocket(context.gon.websocket_gateway_uri);
2012-09-03 22:03:16 +00:00
ws.onopen = function() {
var token = $.cookie("remember_token");
// there is a chance the token is invalid at this point
// but if it is, login should fail, and we can catch that as an error
// and deal with it then.
2012-12-07 00:44:08 +00:00
$("#internal_session_activity").children().remove();
var login = mf.login_with_token(token);
2012-09-03 22:03:16 +00:00
send(login);
};
ws.onmessage = function(e) {
2012-12-07 00:44:08 +00:00
var msg = JSON.parse(e.data);
var inner = msg[msg.type.toLowerCase()];
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
debug_print(msg, inner);
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
if(msg.type == context.JK.MessageType.LOGIN_ACK) {
2012-09-03 22:03:16 +00:00
// we are in... sign in to jam session
2012-12-07 00:44:08 +00:00
var login_jam = mf.login_music_session(context.gon.music_session_id);
send(login_jam);
2012-09-03 22:03:16 +00:00
}
};
ws.onclose = function() {
2012-12-07 00:44:08 +00:00
context.alert("websocket connection closed");
2012-09-03 22:03:16 +00:00
};
2012-12-07 00:44:08 +00:00
};
2012-09-03 22:03:16 +00:00
2012-12-07 00:44:08 +00:00
context.jamsocket = jamsocket;
})(window, jQuery);