Finalising winston logging; Logging timestamp format;
[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 winston = require('winston');
12
13 var control_module = new kiwiModules.Module('Control');
14
15
16 /**
17 * The socket client
18 */
19 function SocketClient (socket) {
20 var that = this;
21
22 this.socket = socket;
23 this.socket_closing = false;
24
25 this.remoteAddress = this.socket.remoteAddress;
26 winston.info('Control connection from %s opened', this.socket.remoteAddress);
27
28 this.bindEvents();
29
30 socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
31
32 this.control_interface = new ControlInterface(socket);
33 _.each(socket_commands, function(fn, command_name) {
34 that.control_interface.addCommand(command_name, fn.bind(that));
35 });
36 }
37
38 SocketClient.prototype.bindEvents = function() {
39 var that = this;
40
41 this.socket.on('close', function() { that.onClose.apply(that, arguments); });
42 };
43
44
45 SocketClient.prototype.unbindEvents = function() {
46 this.socket.removeAllListeners();
47 };
48
49
50 SocketClient.prototype.onClose = function() {
51 this.control_interface.dispose();
52 this.control_interface = null;
53
54 this.unbindEvents();
55 this.socket = null;
56
57 winston.info('Control connection from %s closed', this.remoteAddress);
58 };
59
60
61
62 /**
63 * Available commands
64 * Each function is run in context of the SocketClient
65 */
66 var socket_commands = {
67 quit: function(data) {
68 this.socket.destroy();
69 this.socket_closing = true;
70 },
71 exit: function(data) {
72 this.socket.destroy();
73 this.socket_closing = true;
74 }
75 };
76
77
78 /**
79 * Start the control socket server to serve connections
80 */
81 var server = net.createServer(function (socket) {
82 new SocketClient(socket);
83 });
84 server.listen(8888);
85
86 control_module.on('dispose', function() {
87 server.close();
88 });