glowing-bear/js/websockets.js

69 lines
2.1 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) {
var websocket = null;
var doSend = function(message) {
msgs = message.replace(/[\r\n]+$/g, "").split("\n");
for (var i = 0; i < msgs.length; i++) {
console.log("sent", "&lArr; " + msgs[i]);
$scope.commands.push(msgs[i]);
}
websocket.send(message);
}
var connect = function (hostport, proto, password) {
websocket = new WebSocket("ws://" + hostport + "/weechat");
websocket.onopen = function (evt) {
if (proto == "weechat") {
doSend("init password=" + password + "\ninfo version\ntest\n");
} else {
doSend("PASS " + password + "\r\nNICK test\r\nUSER test 0 * :test\r\n");
}
$scope.connected = true;
$scope.$apply();
}
websocket.onclose = function (evt) {
console.log("disconnected", "Disconnected");
$scope.connected = false;
}
websocket.onmessage = function (evt) {
console.log("recv", "&rArr; " + evt.data);
$scope.commands.push(evt.data);
$scope.$apply();
}
websocket.onerror = function (evt) {
console.log("error", "ERROR: " + evt.data);
}
this.websocket = websocket;
}
var sendMessage = function(message) {
doSend(message);
}
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
$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
}]
);