-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.js
145 lines (118 loc) · 2.64 KB
/
commands.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
var child_process = require( 'child_process' ),
_ = require('underscore'),
exec = child_process.exec,
pathmod = require( 'path' ),
fs = require( 'fs' ),
mimeMagic = require( 'mime-magic' ),
mime = require( 'mime' ),
conf = require( '../config' );
var commands = {
files: function( path, done )
{
var abs = conf.shares.default.path + '/' + path;
fs.readdir( abs, function( err, files )
{
var infoList = [];
if ( err ) {
return handleError( err, done );
}
if ( !files.length ) {
done( {files: infoList} );
return;
}
var fileMapped = _.after( files.length, function() {
done( {
files: infoList
} );
});
_.each( files, function(f) {
var stats = fs.statSync( abs + '/' + f );
var finfo = {};
if ( !stats ) {
finfo = { name: f };
infoList.push( finfo );
fileMapped();
return;
}
finfo = {
name: f,
type: 'application/octet-stream',
size: stats.size,
mtime: stats.mtime,
atime: stats.atime,
ctime: stats.ctime
};
infoList.push( finfo );
if ( stats.isDirectory() ) {
finfo.type = 'dir';
} else if ( stats.isFile() ) {
//TODO: get specific type
mimeLookup( abs + '/' + f, function( mt )
{
finfo.type = mt;
fileMapped();
});
return;
}
fileMapped();
});
});
},
get: function( path, done ) {
var abs = conf.shares.default.path + '/' + path;
var self = this;
fs.stat( abs, function( err, stats ) {
if ( err ) {
return handleError( err, done );
}
if ( !stats.isFile() ) {
return handleError( {error: 'Not a file'}, done );
}
mimeLookup( abs, function( mt ) {
self.res.writeHead(200, {
'Content-Type': mt,
'Content-Length': stats.size
});
var file = fs.createReadStream( abs, {
});
file.resume();
file.on( 'data', function( d ) {
self.res.write( d );
});
file.on( 'end', function() {
//file.end();
done();
});
});
});
}
};
function handleError( err, done )
{
//TODO: RequestHandler should allow the response from done() to set headers,
//or have a way of mapping certain errors to headers.
console.log( 'err', err );
done( {error: err} );
}
function mimeLookup( path, done ) {
var tp = mime.lookup( path, 'unknown' );
if ( tp !== 'unknown' ) {
_.defer( function(){
done( tp );
} );
return;
}
console.log( 'resorting to slow lookup: ', path );
mimeMagic.fileWrapper( path, function( err, mt ) {
if ( err ) {
done( tp );
} else {
done( mt );
}
});
}
mime.define( {
'application/x-gzip': ['gz', 'tgz'],
'text/sql': ['sql']
});
module.exports = commands;