forked from adafruit/Adafruit-WebIDE
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
272 lines (228 loc) · 7.23 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
var express = require('express'),
session = require('express-session'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
serveStatic = require('serve-static'),
morgan = require('morgan'),
app = express(),
expressWs = require('express-ws')(app),
multer = require('multer'),
upload = multer({ dest: './uploads' }),
util = require('util'),
util = require('util'),
site = require('./controllers/site'),
editor = require('./controllers/editor'),
user = require('./controllers/user'),
jsDAV = require("jsDAV/lib/jsdav"),
fs = require('fs'),
path = require('path'),
scheduler = require('./helpers/scheduler'),
fs_helper = require('./helpers/fs_helper'),
debug_helper = require('./helpers/python/debug_helper'),
config = require('./config/config'),
winston = require('winston'),
db = require('./models/webideModel'),
pty = require('node-pty');
var davServer,
HOSTNAME,
REPOSITORY_PATH = path.resolve(__dirname + "/repositories");
var terminals = {}, logs = {};
//check for the existence of the logs directory, if it doesn't
//exist, create it prior to starting the child process.
var exists = fs.existsSync(__dirname + '/logs');
if (!exists) {
fs.mkdirSync(__dirname + '/logs', 0755);
winston.info('created logs folder');
}
//winston.add(winston.transports.File, { filename: __dirname + '/logs/output.log', json: false });
//winston.handleExceptions(new winston.transports.File({ filename: __dirname + '/logs/errors.log', json: false }));
//winston.remove(winston.transports.Console);
winston.info("REPOSITORY_PATH", REPOSITORY_PATH);
//redirect anything with /filesystem in the url to the WebDav server.
app.use(function(req, res, next) {
//res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
if (req.path.indexOf("/filesystem") != -1) {
davServer.exec(req, res);
} else {
next();
}
});
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
//logging
app.use(morgan('tiny'));
app.use(serveStatic(__dirname + '/public'));
app.use(serveStatic(__dirname + '/node_modules/xterm/dist'));
app.use(cookieParser());
var sessionMiddleware = session({
key: 'sid',
secret: 'cat nap',
resave: true,
saveUninitialized: true
});
app.use(sessionMiddleware);
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(methodOverride());
app.use(function(req, res, next) {
res.locals.session = req.session;
next();
});
app.get('/', site.index);
app.get('/editor', editor.index);
app.get('/editor/image', editor.image);
app.post('/editor/upload', upload.single('obj'), editor.upload_file);
app.post('/create/repository', editor.create_repository);
app.get('/setup', user.setup);
app.post('/setup', user.submit_setup);
app.get('/config', user.config);
app.post('/config', user.submit_config);
app.get('/set-datetime', user.set_datetime);
app.post('/terminals', function (req, res) {
var cols = parseInt(req.query.cols),
rows = parseInt(req.query.rows),
cwd = req.query.cwd;
var term = pty.spawn(process.platform === 'win32' ? 'cmd.exe' : 'bash', [], {
name: 'xterm-color',
cols: cols || 80,
rows: rows || 24,
cwd: path.resolve(cwd),
env: process.env
});
console.log('Created terminal with PID: ' + term.pid);
terminals[term.pid] = term;
logs[term.pid] = '';
term.on('data', function(data) {
logs[term.pid] += data;
});
res.send(term.pid.toString());
res.end();
});
app.post('/terminals/:pid/size', function (req, res) {
var pid = parseInt(req.params.pid),
cols = parseInt(req.query.cols),
rows = parseInt(req.query.rows),
term = terminals[pid];
term.resize(cols, rows);
console.log('Resized terminal ' + pid + ' to ' + cols + ' cols and ' + rows + ' rows.');
res.end();
});
app.ws('/terminals/:pid', function (ws, req) {
var term = terminals[parseInt(req.params.pid)];
console.log('Connected to terminal ' + term.pid);
ws.send(logs[term.pid]);
term.on('data', function(data) {
try {
ws.send(data);
} catch (ex) {
// The WebSocket is not open, ignore
}
});
ws.on('message', function(msg) {
try {
msg = JSON.parse(msg);
} catch (e) {
//not json, just a string...
}
if (msg.type === 'input') {
term.write(msg.data.toString() + '\r');
} else {
term.write(msg.toString());
}
});
ws.on('close', function () {
term.kill();
console.log('Closed terminal ' + term.pid);
// Clean things up
delete terminals[term.pid];
delete logs[term.pid];
});
});
app.ws('/editor', editor.editor);
app.use(errorHandler);
serverInitialization(app);
function errorHandler(err, req, res, next) {
winston.error(err);
if (err.name === "InternalOAuthError") {
res.status(500);
res.render('oauth_error', { error: err });
} else {
res.status(500);
res.render('error', { error: err });
}
}
function setHostName(req) {
//set it each time, it's quick, and hostname may change (internal IP vs external IP).
HOSTNAME = req.headers.host;
}
function serverInitialization(app) {
//setup repositories path
var exists = fs.existsSync(REPOSITORY_PATH);
if (!exists) {
fs.mkdirSync(REPOSITORY_PATH, 0777);
winston.info('created repositories folder');
}
//setup symlink to webide home, if it exists:
var has_webide_path = fs.existsSync("/home/webide");
if (has_webide_path) {
//Creating symbolic link to repositories path
winston.info('Linked repository paths: /home/webide/repositories');
if (!fs.existsSync("/home/webide/repositories")) {
fs.symlinkSync(REPOSITORY_PATH, "/home/webide/repositories", 'dir');
}
}
scheduler.initialize_jobs();
start_server(function(server) {
mount_dav(server);
});
}
function start_server(cb) {
db.find('server', function (err, server_data) {
var port;
if (server_data && server_data.port) {
port = server_data.port;
} else if (process.env.PORT) {
port = process.env.PORT
} else {
port = config.editor.port;
}
winston.info('listening on port ' + port);
cb(app.listen(port));
});
}
function mount_dav(server) {
var jsDAV_FS_Tree = require("jsDAV/lib/DAV/backends/fs/tree");
//jsDAV.debugMode = true;
davServer = jsDAV.mount({
path: REPOSITORY_PATH,
mount: '/filesystem',
plugins: ["codesearch", "tree", "filelist", "filesearch", "locks", "mount", "temporaryfilefilter"],
server: server,
standalone: false,
tree: jsDAV_FS_Tree.new(REPOSITORY_PATH)
});
winston.info('webdav filesystem mounted');
}
function cleanup() {
winston.info("process and worker cleanup");
Object.keys(terminals).forEach(function (pid) {
var term = terminals[pid];
console.log('Closed terminal ' + term.pid);
term.kill();
});
debug_helper.kill_debug(false, function() {
//no need to wait for this
});
}
process.on('SIGINT', function() {
winston.info("Shutting down from SIGINT");
cleanup();
process.exit();
});
process.on('uncaughtException', function(err) {
winston.error("Shutting down from uncaughtException");
winston.error(err.stack);
cleanup();
process.exit();
});