forked from FabMo/FabMo-Engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
603 lines (523 loc) · 16.9 KB
/
Copy pathutil.js
File metadata and controls
603 lines (523 loc) · 16.9 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/*
* util.js
*
* This module is full of functions that are of general interest.
*
* Note that this function bears the same name as node's built-in util module.
* This one is require()d with require('./util') while the built-in one with require('util')
*/
var path = require('path');
var log = require('./log').logger('util');
var fs = require('fs');
var q = require('q');
var uuid = require('node-uuid');
var fs = require('fs');
var escapeRE = require('escape-regexp-component');
var exec = require('child_process').exec;
var stream = require('stream');
var util = require('util');
var mime = require('mime');
var restify = require('restify');
var errors = require('restify');
// These are consulted by various upload functions
ALLOWED_EXTENSIONS = ['.nc','.g','.sbp','.gc','.gcode'];
ALLOWED_APP_EXTENSIONS = ['.zip', '.fma'];
GCODE_EXTENSIONS = ['.nc','.g','.gc','.gcode'];
OPENSBP_EXTENSIONS = ['.sbp', '.sbc'];
var MethodNotAllowedError = errors.MethodNotAllowedError;
var NotAuthorizedError = errors.NotAuthorizedError;
var ResourceNotFoundError = errors.ResourceNotFoundError;
function listify(x) {
if(x instanceof Array) {
return x;
} else {
return [x];
}
}
// Execute a command in the shell
// callback - gets the output of the command (stdout)
function doshell(command, callback){
exec(command, function(error, stdout, stderr) {
callback(stdout);
});
}
// Call the 'sync' function (linux)
// Careful - this function waits for a second before returning
function diskSync(callback) {
doshell('sync',function() {
setTimeout(function() {
callback();
}, 1000);
});
}
// Extend an object with the properties of another object.
// force - If true, create new keys in a if they do not already exist. Otherwise, don't.
// Example:
// extend( {a:1,b:2,c:{d:3}}, {a:2,c:{d:4}}) = {a:2,b:2,c:{d:4}}
function extend(a,b, force) {
for(k in b) {
if(a.hasOwnProperty(k) || force) {
if(typeof b[k] === 'object' && b[k] !== null) {
if(typeof a[k] === 'object' && a[k] !== null) {
extend(a[k], b[k], force);
} else {
if(force) {
a[k] = b[k];
} else {
log.warn('Object format error in extend.');
}
}
} else {
a[k] = b[k];
}
}
}
}
// Return the filename given a full path
// TODO - this seems senseless - can't we just use the path module where needed?
exports.filename = function(pathname) {
parts = pathname.split(path.sep);
return parts[parts.legnth-1];
};
// Create and return a unique filename with the same extension as the provided filename
// filename - an existing filename whose extension will be copied for the new filename
// Example:
// createUniqueFilename('/opt/fabmo/example.sbp') -> '12345.sbp'
//
var createUniqueFilename = function (filename) {
var extension = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
return uuid.v1() + (extension ? ('.' + extension) : '');
};
// Simple queue, faster than using array.shift
// Example:
// var q = new Queue()
// q.enqueue('a')
// q.enqueue('b')
// q.enqueue('c')
//
// q.dequeue() -> 'a'
// q.multiDequeue(2) -> ['b','c']
//
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){ return (queue.length - offset); };
this.getContents = function() { return queue; };
this.isEmpty = function(){ return (queue.length === 0); };
this.enqueue = function(item){ queue.push(item); };
this.multiEnqueue = function(iterable) {
iterable.forEach(function(item) {
queue.push(item);
});
}
this.dequeue = function(){
// if the queue is empty, return immediately
if (queue.length === 0) return undefined;
// store the item at the front of the queue
var item = queue[offset];
// increment the offset and remove the free space if necessary
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
// return the dequeued item
return item;
};
// Return up to count items from the queue (in the order they would be retrieved if dequeued)
// count - The number of items to return
// Note: If there are fewer than the number of requested items in the queue
// all items in the queue will be returned.
this.multiDequeue = function(count) {
// If asking for more items than are in the queue, return everything
count = count > queue.length ? queue.length : count;
// store the item at the front of the queue
var items = queue.slice(offset, offset+count);
// add to the offset and remove the free space if necessary
offset += count;
if (offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
// return the dequeued item
return items;
};
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
};
this.clear = function() {
queue = [];
offset = 0;
};
}
// Return true if this is an allowable NC file
// TODO - this sort of functionality should really be moved to the runtimes
// TODO - function name should be camel case in keeping with coding conventions
function allowed_file(filename){
return isGCodeFile(filename) || isOpenSBPFile(filename);
}
function isGCodeFile(pathname) {
return (GCODE_EXTENSIONS.indexOf(path.extname(pathname).toLowerCase()) !== -1)
}
function isOpenSBPFile(pathname) {
return (OPENSBP_EXTENSIONS.indexOf(path.extname(pathname).toLowerCase()) !== -1)
}
// Return true if this is an allowable file to contain an app.
// TODO - This check should live in the app manager, really.
function allowedAppFile(filename) {
if (ALLOWED_APP_EXTENSIONS.indexOf(path.extname(filename).toLowerCase()) !== -1) {
return true;
}
else {
return false;
}
}
/**
* Move a file from src to dest, avoiding cross-device rename failures.
* This method will first try fs.rename and call the supplied callback if it succeeds. Otherwise
* it will pipe the conent of src into dest and unlink src upon completion.
*
* This might take a little more time than a single fs.rename, but it avoids error when
* trying to rename files from one device to the other.
*/
var move = function (src, dest, cb) {
var renameDeferred = q.defer();
fs.rename(src, dest, function (err) {
if (err) {
renameDeferred.reject(err);
}
else {
renameDeferred.resolve();
}
});
renameDeferred.promise.then(function () {
// rename worked
return cb(null);
}, function (err) {
log.warn('io.move: standard rename failed, trying stream pipe... (' + err + ')');
// rename didn't work, try pumping
var is = fs.createReadStream(src),
os = fs.createWriteStream(dest);
is.pipe(os);
is.on('end', function () {
fs.unlinkSync(src);
cb(null);
});
is.on('error', function (err) {
return cb(err);
});
os.on('error', function (err) {
return cb(err);
});
});
};
function serveStatic(opts) {
opts = opts || {};
/*
assert.object(opts, 'options');
assert.string(opts.directory, 'options.directory');
assert.optionalNumber(opts.maxAge, 'options.maxAge');
assert.optionalObject(opts.match, 'options.match');
assert.optionalString(opts.charSet, 'options.charSet');
*/
var p = path.normalize(opts.directory).replace(/\\/g, '/');
var re = new RegExp('^' + escapeRE(p) + '/?.*');
function serveFileFromStats(file, err, stats, isGzip, req, res, next) {
if (err) {
next(new ResourceNotFoundError(err,
req.path()));
return;
} else if (!stats.isFile()) {
next(new ResourceNotFoundError('%s does not exist', req.path()));
return;
}
if (res.handledGzip && isGzip) {
res.handledGzip();
}
var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
fstream.once('open', function (fd) {
res.cache({maxAge: maxAge});
res.set('Content-Length', stats.size);
res.set('Content-Type', mime.lookup(file));
res.set('Last-Modified', stats.mtime);
if (opts.charSet) {
var type = res.getHeader('Content-Type') +
'; charset=' + opts.charSet;
res.setHeader('Content-Type', type);
}
if (opts.etag) {
res.set('ETag', opts.etag(stats, opts));
}
res.writeHead(200);
fstream.pipe(res);
fstream.once('end', function () {
next(false);
});
});
}
function serveNormal(file, req, res, next) {
fs.stat(file, function (err, stats) {
if (!err && stats.isDirectory() && opts.default) {
// Serve an index.html page or similar
file = path.join(file, opts.default);
fs.stat(file, function (dirErr, dirStats) {
serveFileFromStats(file,
dirErr,
dirStats,
false,
req,
res,
next);
});
} else {
serveFileFromStats(file,
err,
stats,
false,
req,
res,
next);
}
});
}
function serve(req, res, next) {
var uricomp = decodeURIComponent(req.path());
var file = path.join(opts.directory, uricomp);
if (req.method !== 'GET' && req.method !== 'HEAD') {
next(new MethodNotAllowedError(req.method));
return;
}
if (!re.test(file.replace(/\\/g, '/'))) {
next(new NotAuthorizedError(req.path()));
return;
}
if (opts.match && !opts.match.test(file)) {
next(new NotAuthorizedError(req.path()));
return;
}
if (opts.gzip && req.acceptsEncoding('gzip')) {
fs.stat(file + '.gz', function (err, stats) {
if (!err) {
res.setHeader('Content-Encoding', 'gzip');
serveFileFromStats(file,
err,
stats,
true,
req,
res,
next);
} else {
serveNormal(file, req, res, next);
}
});
} else {
serveNormal(file, req, res, next);
}
}
return (serve);
}
// TODO better error handling here
// TODO bad argument name
// Return a tree structure that represents a walk of the specified directory
// filename - The name of the directory to walk ()
// Each node in the returned object has the following properties:
// path : The path of the object
// text : The filename only
// name : The filename (again? TODO: Why?)
// type : 'file' for files, 'dir' for directories
// children : A list of child nodes, if this is a directory
function walkDir(filename) {
var stats = fs.lstatSync(filename),
info = {
path: filename,
text: path.basename(filename),
name: path.basename(filename)
};
if (stats.isDirectory()) {
info.type = "dir";
info.children = fs.readdirSync(filename).map(function(child) {
return walkDir(filename + '/' + child);
});
} else {
// Assuming it's a file. In real life it could be a symlink or
// something else!
info.type = "file";
info.children = null;
}
return info;
}
// Get the size of this file
// path - Path to check
// cb - Callback gets the size as an integer number of bytes, or error
// TODO - is this really needed?
function getSize (path, cb) {
fs.stat(path, function (err, stats) {
if(err) {
cb(err);
} else {
cb(null, stats.size);
}
});
}
// TODO: I am pretty sure this function is terrible.
// Look at where it's used, and re-evaluate the need for it. I think it should be factored out.
function fixJSON(json) {
var retval = {};
for(var key in json) {
if (typeof json[key] === 'object') {
var value = fixJSON(json[key]);
} else {
var value = Number(json[key]);
if(typeof value === 'undefined' || isNaN(value)) {
if(json[key] === 'true') {
value = true;
} else if(json[key] === 'false') {
value = false;
} else {
value = json[key];
}
}
}
if(key[0] === '_') {
key = key.slice(1);
}
retval[key] = value;
}
return retval;
}
// Watchdog object
// Simple object that keeps a recurring timer that, if it expires,
// will exit the application. Timer can be refreshed by the reset() method.
// Works like a watchdog in an embedded system that resets the CPU if a process runs away.
// TODO: Not sure that this is currently used, but it doesn't do anything. (exit stuff commented out)
// I think a more useful watchdog would accept a callback in its constructor, and simply call that
// in the case that it expires.
function Watchdog(timeout,exit_code){
var watchdog_flag;
var watchdog_timeout=timeout||1000;
var watchdog_exit_code=exit_code||20;
watchdog_exit = function(){
//throw new Error("G2 is not responding");
//process.exit(this.watchdog_exit_code);
};
this.start = function(){
if(this.watchdog_flag===undefined){
this.watchdog_flag=setTimeout(watchdog_exit,watchdog_timeout);
}
else{
this.reset();
}
};
this.stop= function(){
if(this.watchdog_flag){
clearTimeout(this.watchdog_flag);
this.watchdog_flag=undefined;
}
};
this.reset = function(){
if(this.watchdog_flag){
clearTimeout(this.watchdog_flag);
this.watchdog_flag=setTimeout(watchdog_exit,watchdog_timeout);
}
};
}
// Convenience function for getting the client IP address from a restify request.
var getClientAddress = function (req) {
return (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
};
// Check to see if something is a number (strings that parse to numbers, for example)
var isANumber = function(n) {
try {
var n = Number(n);
return n == n;
} catch(e) {
return false;
}
}
// Unit conversion
var mm2in = function(mm) {
return mm/25.4;
}
// Unit conversion
var in2mm = function(inch) {
return inch*25.4;
}
// Unit type normalizer
var unitType = function(u) {
u = String(u).trim().toLowerCase()
switch(u) {
case '0':
case 'in':
return 'in';
break;
case '1':
case 'mm':
return 'mm';
break;
default:
throw new Error('Invalid unit type specifier: ' + u);
break;
}
}
function LineNumberer(options) {
// allow use without new
if (!(this instanceof LineNumberer)) {
return new LineNumberer(options);
}
this.count = 0;
// init Transform
stream.Transform.call(this, options);
}
util.inherits(LineNumberer, stream.Transform);
LineNumberer.prototype._transform = function(chunk, enc, next) {
var data = chunk.toString();
if (this._lastLineData) { data = this._lastLineData + data; }
var lines = data.split('\n');
this._lastLineData = lines.splice(lines.length-1,1)[0];
block = []
for(var i=0; i<lines.length; i++) {
this.count += 1;
//this.push("N" + this.count + " " + lines[i] + '\n');
block.push("N" + this.count + " " + lines[i]);
}
this.push(block.join('\n'))
next();
};
LineNumberer.prototype._flush = function(done) {
if (this._lastLineData) { this.push(this._lastLineData); }
this._lastLineData = null;
done();
};
var countLineNumbers = function(filename, callback) {
var i;
var lines = 0;
require('fs').createReadStream(filename)
.on('data', function(chunk) {
for (i=0; i < chunk.length; ++i)
if (chunk[i] == 10) lines++;
})
.on('end', function() {
callback(null, lines)
});
}
exports.countLineNumbers = countLineNumbers;
exports.LineNumberer = LineNumberer;
exports.serveStatic = serveStatic;
exports.getSize = getSize;
exports.Queue = Queue;
exports.Watchdog = Watchdog;
exports.allowed_file = allowed_file;
exports.allowedAppFile = allowedAppFile;
exports.move = move;
exports.walkDir = walkDir;
exports.createUniqueFilename = createUniqueFilename;
exports.fixJSON = fixJSON;
exports.extend = extend;
exports.doshell = doshell;
exports.getClientAddress = getClientAddress;
exports.isANumber = isANumber;
exports.in2mm = in2mm;
exports.mm2in = mm2in;
exports.unitType = unitType;
exports.diskSync = diskSync;