-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
212 lines (182 loc) · 6.94 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env node
'use strict';
require('./public/vendor/telegraph.js');
class TerminalServer {
constructor() {
console.log("Terminal server starting...");
var express = require('express');
this.app = express();
var http = require('http').Server(this.app);
this.io = require('socket.io')(http);
this.db = require('monk')('localhost/nexus');
this.cmds = {};
this.responses = {};
this.sessions = {};
http.listen(3000, this.appListening.bind(this));
var bodyParser = require('body-parser')
this.app.use(bodyParser.json());
this.app.use(express.static(__dirname + '/public'));
this.app.use(function(req, res, next){
res.locals.showTests = (this.app.get('env') !== 'production' &&
req.query.test === '1');
next();
}.bind(this));
this.app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log("ERROR", err);
});
this.loadModules('apps', this.registerApp.bind(this));
this.loadModules('responses', this.registerResponder.bind(this));
var ErrorResponse = require('./lib/errorresponse.js');
this.errorResponse = new ErrorResponse();
this.setupSocketComms();
this.setupRoutes();
this.setupTemplates();
this.globalLoginComplete = false;
this.options = this.db.get('options');
this.options.count({ 'has_logged_in': true }).then(function(result) {
this.globalLoginComplete = (result > 0);
console.log("global login state is", this.globalLoginComplete);
}.bind(this));
}
loadModules(libDir, callback) {
var dir = 'lib/' + libDir + '/';
var normalizedPath = require("path").join(__dirname, dir);
require("fs").readdirSync(normalizedPath).forEach(function(file) {
var theModule = require("./" + dir + file);
var moduleInstance = new theModule(this.db);
callback(moduleInstance.getInputExpr(), theModule);
}.bind(this));
}
setupRoutes() {
this.app.get('/', function(req, res) {
if (req.query.resetlogin==='y') {
console.log(" --- RESETTING LOGIN AUTH");
this.options = this.db.get('options');
this.options.findOneAndUpdate(
{ 'has_logged_in': true },
{ 'has_logged_in': false }
).then(function(result) {
console.log("Login reset result:", result);
if (result) this.globalLoginComplete = false;
}.bind(this));
}
this.bootlines = require('./lib/bootlines.js');
res.render('home', { bootlines: this.bootlines.get() });
}.bind(this));
}
setupTemplates() {
this.handlebars = require('express3-handlebars')
.create({ defaultLayout:'main' });
this.app.engine('handlebars', this.handlebars.engine);
this.app.set('view engine', 'handlebars');
}
setupSocketComms() {
this.io.on('connection', this.onClientConnected.bind(this));
}
onClientConnected(client) {
console.log('User '+client.id+' connected.');
this.sessions[client.id] = {
currentApp: null,
lastCmd: null
};
client.on('disconnect', function(){
console.log('User '+client.id+' disconnected.');
delete this.sessions[client.id];
}.bind(this));
client.on('login', function() {
console.log("Client "+client.id+" sent LOGIN");
this.allowSocketInputFor(client);
}.bind(this));
}
allowSocketInputFor(client) {
client.on('command', function(cmd) {
console.log('User '+client.id+' sent command "'+cmd+'".');
if (!this.globalLoginComplete) {
this.processLoginAttempt(client, cmd);
}
else {
this.processCommand(client, cmd);
}
}.bind(this));
client.emit('begin', this.globalLoginComplete);
}
disableSocketInputFor(client) {
client.on('command', function(){});
client.emit('end');
}
processLoginAttempt(client, cmd) {
if (cmd.toLowerCase()==='2016-10-29 11:00:00') {
// set the option - TODO
this.options.findOneAndUpdate({ 'has_logged_in': false }, { 'has_logged_in': true }).then(function(result) {
console.log("result of updating has_logged_in", result);
});
this.globalLoginComplete = true;
this.respond(client, 'Chronal adjustment confirmed, awaiting orbital insertion.');
this.disableSocketInputFor(client);
}
else {
this.respond(client, 'Error in chronal adjustment, please re-calculate.');
// this.disableSocketInputFor(client);
}
}
processCommand(client, cmd) {
var responseMsg = 'Unknown Command';
var session = this.sessions[client.id];
if (session.currentApp) {
session.currentApp.processCommand(cmd);
}
else {
var newApp = this.findApp(cmd);
if (newApp) {
session.currentApp = new newApp(this.db);
session.currentApp.on('consoleapp:output', s => this.respond(client, s.s));
session.currentApp.on('consoleapp:end', () => delete session.currentApp);
session.currentApp.begin();
}
else {
var response = this.getResponder(cmd, this.db);
if (!response) {
response = this.errorResponse.getResponse('');
}
this.respond(client, response);
}
}
}
respond(client, msg) {
console.log('Client', client.id, '- sending response "'+msg+'"');
client.emit('response', msg);
}
registerApp(inputStr, className) {
console.log("Registered app", className.name);
this.cmds[inputStr] = className;
}
registerResponder(inputExpr, className) {
console.log("Registered responder", className.name);
this.responses[inputExpr] = className;
}
findApp(s) {
if (s in this.cmds) {
return this.cmds[s];
}
return false;
}
getResponder(s, db) {
for(var i in this.responses) {
var r = new RegExp(i, 'i');
if (s.match(r)) {
var response = new this.responses[i](db);
response.on('globallogout', function() {
console.log("global logout");
this.globalLoginComplete = false;
}.bind(this));
return response.getResponse(s);
}
}
return false;
}
appListening() {
console.log('Express running on port 3000');
}
}
var server = new TerminalServer();