-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
265 lines (232 loc) · 7.26 KB
/
index.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
const http = require('http');
const exec = require('child_process').exec;
const formidable = require('formidable');
const fs = require('fs');
const crypto = require('crypto');
const mkdirp = require('mkdirp');
const path = require('path');
const slug = require('slug');
const raven = require('raven');
const mustache = require('mustache');
raven.config(process.env.SENTRY_DSN).install();
const server = process.env.SERVER || 'http://localhost:1234';
const base64urltok = (l) => {
return crypto.randomBytes(l).toString('base64')
.replace(/\//g, '-')
.replace(/=/g, '');
}
const mkdir = (req, res) => {
var hash =
base64urltok(2) +
'/' +
base64urltok(22);
var target = 'data/' + hash;
mkdirp('./' + target, err => {
res.writeHead(302, {
'Location': '/dir/' + target
//add other headers here...
});
res.end();
});
}
const upload = (req, res) => {
const form = new formidable.IncomingForm();
var paths = [],
ajax = false;
// console.log('File path on Upload:', req.file_path);
form.uploadDir = req.file_path;
form.on('error', function(error) {
res.end(error.message);
});
form.on('fileBegin', function(name, file) {
//rename the incoming file to the file's name
//TODO: Possible problem when using POSIX file paths on Windows.
//DONE: Using path.sep instead of "/" (which is not Windows compliant).
// file.path = form.uploadDir + "/" + encodeURIComponent(file.name);
// console.log('Upload Directory:', form.uploadDir);
// console.log('File Name:', file.name);
// console.log('Encoded File Name:', encodeURIComponent(file.name));
file.path = form.uploadDir + path.sep + encodeURIComponent(file.name);
// console.log('File Path:', file.path);
paths.push(file.path);
});
form.on('field', function(name, value) {
//TODO: There is a hidden input named ajax with a value set to 1 on the dir.html file. Why do we have to check for the field here if we know it is hardcoded (and under normal circumstances, unchangeable) in the form?
if (name === 'ajax') {
ajax = true;
}
});
form.on('end', function() {
var content, contentType, success = true;
if (paths.length) {
// console.log('paths', paths);
// New paths:
var newfiles = paths.map(function(f) {
return server + f.replace(/^.\/public/g, '');
});
// TODO: Whas this variable (message) initialized somewhere? Am I missing something?
message = "saved to " + newfiles.join(',');
} else {
message = "no file uploaded";
success = false;
}
if (ajax) {
content = JSON.stringify({
success: success,
message: message,
dir: form.uploadDir.replace(/^.\/public/g, '')
});
contentType = 'application/json';
} else {
content = message;
contentType = 'text/plain';
}
res.writeHead(success ? 200 : 400, {
'Content-Type': contentType
});
res.write(content)
res.end();
});
form.parse(req);
}
// Used to determine the versioning of frontend assets.
exec(`git rev-parse --short HEAD`, function(err, stdout, stderr) {
let version = "0";
if (err) {
console.log("ERROR: When loading git version:", err);
return;
}
if (stderr) {
console.log("ERROR: stderr when loading git version:", stderr);
return;
}
version = stdout.toString().replace(/\s/g, '');
console.log("Setting version to revision:", version);
REVISION = version;
});
let _version = null; // overwrite me.
const ls = (req, res) => {
// directoryindex.
fs.readdir(req.file_path, (error, files) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404);
res.end("404");
}
res.writeHead(500);
return res.end('error: ' + error.code + ' ..\n');
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
return res.end(JSON.stringify(files), 'utf-8');
})
}
const cat = (req, res) => {
var extname = path.extname(req.file_path);
var contentType = 'application/octet-stream';
switch (extname) {
case '.txt':
contentType = 'text/plain';
break;
case '.htm':
case '.html':
contentType = 'text/html';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
}
fs.readFile(req.file_path, function(error, content) {
if (error) {
console.error(error);
if (error.code === 'ENOENT') {
return http404(res);
} else {
res.writeHead(500);
res.end('error: ' + error.code + ' ..\n');
}
} else {
if (extname === '.html' || extname === '.htm') {
content = mustache.to_html(content.toString(), {
REVISION: REVISION
});
}
res.writeHead(200, {
'Content-Type': contentType
});
res.end(content, 'utf-8');
}
});
}
const http404 = (res) => {
res.writeHead(404);
res.end("no such file.");
}
const del = (req, res) => {
// console.log('Path on delete', req.file_path);
fs.unlink(req.file_path, (error) => {
if (error) {
console.error(error);
if (error.code === 'ENOENT') {
return http404(res);
} else {
res.writeHead(500);
res.end('error: ' + error.code + ' ..\n');
}
} else {
res.writeHead(204);
res.end();
}
});
}
http.createServer((req, res) => {
var _tmp = req.url.split("?");
const query = _tmp[1];
var toks = _tmp[0].split("/");
req.file_path = toks.slice(2).join(path.sep);
var command = toks[1];
if (req.method === 'DELETE') {
return del(req, res);
}
if (req.method === 'POST') {
return upload(req, res);
}
if (command === 'fail') {
throw new Error('Test Trace');
}
if (command === '') {
command = 'cat';
req.file_path = `public${path.sep}index.html`;
}
if (command === 'ls') {
if (toks[2] === 'data' &&
toks.length === 5 &&
toks[4].length > 0) {
return ls(req, res);
}
} else if (command === 'dir') {
req.file_path = `public${path.sep}dir.html`;
return cat(req, res);
} else if (command === 'cat') {
let root = req.file_path.split(path.sep)[0];
if (root === 'data' || root === 'public') {
return cat(req, res);
}
} else if (command === 'mkdir') {
return mkdir(req, res);
}
return http404(res);
}).listen(1234);