Merge pull request #336 from M2Ys4U/userbox
[KiwiIRC.git] / server_modules / control.js
1 /**
2 * Server control via TCP socket
3 *
4 * Listens on localhost:8888 by default
5 */
6
7 var net = require('net'),
8 kiwiModules = require('../server/modules'),
9 ControlInterface = require('../server/controlinterface.js'),
10 _ = require('lodash');
11
12 var control_module = new kiwiModules.Module('Control');
13
14
15 /**
16 * The socket client
17 */
18 function SocketClient (socket) {
19 var that = this;
20
21 this.socket = socket;
22 this.socket_closing = false;
23
24 this.remoteAddress = this.socket.remoteAddress;
25 console.log('Control connection from ' + this.socket.remoteAddress + ' opened');
26
27 this.bindEvents();
28
29 socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
30
31 this.control_interface = new ControlInterface(socket);
32 _.each(socket_commands, function(fn, command_name) {
33 that.control_interface.addCommand(command_name, fn.bind(that));
34 });
35 }
36
37 SocketClient.prototype.bindEvents = function() {
38 var that = this;
39
40 this.socket.on('close', function() { that.onClose.apply(that, arguments); });
41 };
42
43
44 SocketClient.prototype.unbindEvents = function() {
45 this.socket.removeAllListeners();
46 };
47
48
49 SocketClient.prototype.onClose = function() {
50 this.control_interface.dispose();
51 this.control_interface = null;
52
53 this.unbindEvents();
54 this.socket = null;
55
56 console.log('Control connection from ' + this.remoteAddress + ' closed');
57 };
58
59
60
61 /**
62 * Available commands
63 * Each function is run in context of the SocketClient
64 */
65 var socket_commands = {
66 quit: function(data) {
67 this.socket.destroy();
68 this.socket_closing = true;
69 },
70 exit: function(data) {
71 this.socket.destroy();
72 this.socket_closing = true;
73 }
74 };
75
76
77 /**
78 * Start the control socket server to serve connections
79 */
80 var server = net.createServer(function (socket) {
81 new SocketClient(socket);
82 });
83 server.listen(8888);
84
85 control_module.on('dispose', function() {
86 server.close();
87 });