glowing-bear/js/websockets.js

102 lines
2.9 KiB
JavaScript
Raw Normal View History

2013-02-18 00:49:42 +01:00
var weechat = angular.module('weechat', []);
weechat.factory('connection', ['$rootScope', function($scope) {
protocol = new Protocol();
2013-02-18 00:49:42 +01:00
var websocket = null;
2013-02-18 00:49:42 +01:00
var doSend = function(message) {
msgs = message.replace(/[\r\n]+$/g, "").split("\n");
for (var i = 0; i < msgs.length; i++) {
console.log('=' + msgs[i] + '=');
$scope.commands.push("SENT: " + msgs[i]);
2013-02-18 00:49:42 +01:00
}
websocket.send(message);
}
var connect = function (hostport, proto, password) {
websocket = new WebSocket("ws://" + hostport + "/weechat");
websocket.binaryType = "arraybuffer"
2013-02-18 00:49:42 +01:00
websocket.onopen = function (evt) {
if (proto == "weechat") {
doSend("init compression=off\nversion\n");
2013-02-18 00:49:42 +01:00
} else {
doSend("PASS " + password + "\r\nNICK test\r\nUSER test 0 * :test\r\n");
}
$scope.connected = true;
$scope.$apply();
}
2013-02-18 00:49:42 +01:00
websocket.onclose = function (evt) {
console.log("disconnected", "Disconnected");
$scope.connected = false;
}
2013-02-18 00:49:42 +01:00
websocket.onmessage = function (evt) {
protocol.setData(evt.data);
message = protocol.parse()
console.log(evt);
$scope.commands.push("RECV: " + evt.data + " TYPE:" + evt.type) ;
parseMessage(message);
data = evt.data;
2013-02-18 00:49:42 +01:00
$scope.$apply();
}
2013-02-18 00:49:42 +01:00
websocket.onerror = function (evt) {
console.log("error", "ERROR: " + evt.data);
}
this.websocket = websocket;
}
var parseMessage = function(message) {
console.log(message['id']);
if (message['id'] == '_buffer_line_added') {
types[message['id']](message);
}
console.log(message);
}
var handleBufferLineAdded = function(message) {
var buffer_line = message['objects'][0]['content'][0]['message'];
$scope.buffer.push(buffer_line);
}
2013-02-18 00:49:42 +01:00
var sendMessage = function(message) {
message = message + "\n"
2013-02-18 00:49:42 +01:00
doSend(message);
}
var types = {
_buffer_line_added: handleBufferLineAdded
}
2013-02-18 00:49:42 +01:00
return {
connect: connect,
sendMessage: sendMessage
}
}]);
weechat.controller('WeechatCtrl', ['$rootScope', '$scope', 'connection', function ($rootScope, $scope, connection) {
$rootScope.commands = []
2013-02-16 19:18:14 +01:00
$rootScope.buffer = []
2013-02-16 19:18:14 +01:00
$scope.hostport = "localhost:9001"
$scope.proto = "weechat"
$scope.password = ""
2013-02-18 00:49:42 +01:00
$scope.sendMessage = function() {
connection.sendMessage($scope.command);
$scope.command = "";
},
2013-02-16 19:18:14 +01:00
2013-02-18 00:49:42 +01:00
$scope.connect = function() {
connection.connect($scope.hostport, $scope.proto, $scope.password);
2013-02-16 19:18:14 +01:00
}
2013-02-18 00:49:42 +01:00
}]
);