-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstatic.js
379 lines (322 loc) · 15 KB
/
static.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
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
// static content + less processing
// (c)copyright 2015 by Gerald Wodni <[email protected]>
"use strict";
var url = require("url");
var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var less = require("less");
var imageMagick = require("gm").subClass({imageMagick: true});
var _ = require("underscore");
module.exports = function _static( k, opts ) {
var guardRegex = new RegExp( '\\' + path.sep, 'g' );
function guard( prefix, req, res, callback ) {
/* normalize to os-independent path */
var pathname = decodeURI( url.parse( req.url ).pathname );
pathname = path.normalize( pathname );
pathname = pathname.replace( guardRegex, '/' );
/* contain in directory */
if( pathname.indexOf( ".." ) >= 0 )
return k.err.renderHttpStatus( req, res, 403 );
callback( pathname.indexOf( prefix ) == 0, pathname );
};
async function renderBrowseDirectory( req, res, prefix, dirpath, opts ) {
const items = await fs.promises.readdir( dirpath );
const dirs = [];
const files = [];
const upLink = path.dirname( prefix );
if( upLink != "/" )
dirs.push({
name: "..",
link: upLink,
});
let indexHtml = null;
let indexMarkdown = null;
for( let item of items ) {
const itemPath = path.join( dirpath, item );
const stat = await fs.promises.stat( itemPath )
const obj = {
name: item,
link: path.join( prefix, item ),
path: itemPath,
};
if( stat.isDirectory() ) {
obj.link += "/";
dirs.push( obj );
}
else {
files.push( obj );
console.log( opts.indexHtml, obj.name );
if( opts.indexHtml && obj.name == "index.html" )
indexHtml = (await fs.promises.readFile( itemPath )).toString();
else if( opts.indexMarkdown && obj.name == "index.md" )
indexMarkdown = (await fs.promises.readFile( itemPath )).toString();
}
}
k.jade.render( req, res, "browseDir", { prefix, dirs, files, indexHtml, indexMarkdown } );
}
function prefixServeStatic( router, prefix, opts = {} ) {
router.use( function( req, res, next ) {
guard( prefix, req, res, async function( prefixOkay, pathname ) {
if( prefixOkay ) {
try {
const filepath = k.hierarchy.lookupFileThrow( req.kern.website, pathname );
const stat = await fs.promises.stat( filepath );
if( !stat.isDirectory() )
return res.sendfile( filepath );
/* list browsable directoy (if enable via opts.browse) */
if( opts.browse )
return renderBrowseDirectory( req, res, pathname, filepath, opts );
return k.err.renderHttpStatus( req, res, 404 );
}
catch( err ) {
return next( err );
}
}
next();
});
});
};
/* serve static content like images and javascript */
function serveStatic( directory, req, res ) {
var filename = req.requestman.filename( 'file' );
var filepath = k.hierarchy.lookupFileThrow( req.kern.website, path.join( directory, filename ) );
res.header("Cache-Control", "max-age=" + 12*60*60);
res.sendfile( filepath );
};
function prefixCache( prefix, originPrefix, generator, opts ) {
opts = opts || {};
(opts.router || k.app).get( prefix + "*", function( req, res, next ) {
/* capture esacape attempts */
guard( prefix, req, res, function( prefixOkay, pathname ) {
if( prefixOkay ) {
/* rename source */
var targetExtension = path.extname( pathname );
if( opts.sourceExtension )
pathname = pathname.slice( 0, -targetExtension.length ) + opts.sourceExtension;
/* get real prefixed path */
pathname = pathname.replace( new RegExp( "^" + prefix ), originPrefix );
/* rewrite pathes */
var changeCacheExtension = false;
if( opts.pathRewrite ) {
const pathes = opts.pathRewrite( pathname );
if( typeof pathes !== "string" ) {
if( pathes.hasOwnProperty( "redirect" ) )
return res.redirect( pathes.redirect );
pathname = pathes.source;
changeCacheExtension = pathes.targetExtension;
}
else
pathname = pathes;
}
/* get original and cache-filename */
var filepath = k.hierarchy.lookupFileThrow( req.kern.website, pathname );
var cachepath = filepath.replace( /^websites\//, "cache" + prefix )
/* rename target (from hierarchy path to be safe) */
if( opts.sourceExtension )
cachepath = cachepath.slice( 0, -opts.sourceExtension.length ) + targetExtension;
if( changeCacheExtension !== false )
cachepath = cachepath.slice( 0, -path.extname( cachepath ).length ) + changeCacheExtension;
/* file cached? */
fs.stat( cachepath, function( err, cacheStat ) {
function sendIt() {
if( opts.contentType )
res.header( 'Content-Type', opts.contentType );
const fullpath = path.join( k.kernOpts.rootFolder, cachepath );
res.sendFile( fullpath );
}
/* exists -> check age */
if( err == null )
return fs.stat( filepath, function( err, fileStat ) {
/* send cached file */
if( err || fileStat.mtimeMs <= cacheStat.mtimeMs )
return sendIt();
/* generate */
console.log( "Refresh prefixCache: " + filepath );
generator( filepath, cachepath, function( err ) {
if( err ) {
console.log( "GeneratorRefresh-ERROR: ", err );
return next( err );
}
sendIt();
});
});
/* create cache directory */
mkdirp( path.dirname( cachepath ), function( err ) {
if( err )
return next( err );
generator( filepath, cachepath, function( err ) {
if( err ) {
console.log( "Generator-ERROR: ", err );
return next( err );
}
sendIt();
});
});
});
}
else
next();
});
});
}
function single(filename, mimeType) {
return function( req, res, next ) {
var file = k.hierarchy.createReadStream( req.kern.website, filename );
res.header('Content-Type', mimeType);
file.pipe( res );
}
}
function route() {
prefixCache( "/images-preview/", "/images/", function( filepath, cachepath, next ) {
imageMagick( filepath )
.autoOrient()
.resize( 200, 200 + "^" )
.gravity( "Center" )
.extent( 200, 200 )
.write( cachepath, next );
});
prefixCache( "/images-gallery/", "/images/", function( filepath, cachepath, next ) {
imageMagick( filepath )
.autoOrient()
.resize( 1024, 1024 )
.write( cachepath, next );
});
k.app.get("/images-download/*", function( req, res, next ) {
/* add disposition header and route to image */
req.url = req.url.replace( /^\/images\-download\//, "/images/" );
res.header("Content-Disposition", path.basename( req.url ));
next();
});
prefixServeStatic( k.app, "/images/" );
prefixCache( "/files-preview/", "/files/", function( filepath, cachepath, next ) {
var extension = path.extname( filepath );
if( [".jpg", ".jpeg", ".png", ".gif"].indexOf( extension ) < 0 )
return next( new Error( `Unsupported file type '${extension}'` ) );
imageMagick( filepath )
.autoOrient()
.resize( 200, 200 + "^" )
.gravity( "Center" )
.extent( 200, 200 )
.write( cachepath, next );
});
k.app.get("/files-download/*", function( req, res, next ) {
req.url = req.url.replace( /^\/files\-download\//, "/files/" );
res.header("Content-Disposition", path.basename( req.url ));
next();
});
prefixServeStatic( k.app, "/media/" );
//app.get("/images/:file", function( req, res, next ) {
// serveStatic( "images", req, res );
//});
k.app.get("/js/:file", function _static_js( req, res, next ) {
serveStatic( "js", req, res );
});
k.app.get("/js/:directory/:file", function _static_js_dir( req, res, next ) {
serveStatic( "js/" + req.requestman.filename( 'directory' ), req, res );
});
k.app.get("/fonts/:file", function _static_fonts( req, res, next ) {
serveStatic( "fonts", req, res );
});
/* less, circumvent path-processing */
var lessCache = k.cache( "less" );
function lessRequest( prefix, preloader, plugins = ( req => [] ) ) {
return function _lessRequest( req, res, next ) {
var filename = req.path.substring( prefix.length );
var filepath = k.hierarchy.lookupFile( req.kern.website, path.join( 'css', filename ) );
/* static css found, serve it */
if( filepath != null )
return res.sendfile( filepath );
/* dynamic less */
filepath = k.hierarchy.lookupFile( req.kern.website, path.join( 'css', filename.replace( /\.css$/g, '.less' ) ) );
if( filepath == null )
return next();
lessCache.get( { filename: filepath, website: req.kern.website }, function( err, data ) {
if( err )
return next( err );
if( data ) {
res.set( 'Content-Type', 'text/css' );
res.send( data );
return;
}
new Promise( (fulfill, reject) => {
fs.readFile( filepath, 'utf8', ( err, data ) => {
if( err )
reject( err );
else
fulfill( data );
});
})
.then( data => {
if( preloader )
return preloader( req, data );
return Promise.resolve( data );
})
.then( (data) => {
/* parse less & convert to css */
return less.render( data.toString(), {
filename: filepath,
paths: k.hierarchy.paths( req.kern.website, 'css' ),
plugins: plugins( req )
});
})
.then( output => {
res.set( 'Content-Type', 'text/css' );
res.send( output.css );
console.log( "LESS-OK:".bold.green, filepath, output.imports );
lessCache.set( {
filename: filepath,
website: req.kern.website,
dependencies: output.imports
}, output.css );
})
.catch( err => {
console.log( "LESS-Error".bold.red, err.toString() );
next( err );
});
});
};
}
k.app.get("/css/dynamic/*", lessRequest( "/css/dynamic/",
function _preloader( req, data ) {
return new Promise( (fulfill, reject) => {
k.site.getTarget( req, (err, _website) => {
req.kern.adminMenu = req.kern.site.registeredSiteModules["admin"].getMenu( req, { showAll: true } );
if( err ) return reject( err );
fulfill( data );
})
});
},
function _plugins( req ) {
return [{
install: ( l, pM, f ) => {
f.add( "kernAdminMenu", () => new l.tree.Value( _.pluck( req.kern.adminMenu, "link" ) ) );
f.add( "kernAdminMenuPropery", ( link, keys, defaultValue ) => {
link = link.value; keys = keys.value.split(".");
var item = _.find( req.kern.adminMenu, item => item.link == link );
var value = item;
while( keys.length ) {
var key = keys.shift();
if( _.has( value, key ) )
value = value[key];
else
return defaultValue;
}
return value;
});
}
}]
}
));
k.app.get("/css/*", lessRequest( "/css/" ) );
k.app.get("/css/:directory/:file", function _static_css_dir( req, res, next ) {
serveStatic( "css/" + req.requestman.filename( 'directory' ), req, res );
});
}
return {
prefixServeStatic: prefixServeStatic,
prefixCache: prefixCache,
single: single,
route: route
}
}