forked from ClayLanzino/lucee-docs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathApplication.cfc
425 lines (384 loc) · 13.8 KB
/
Application.cfc
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
component {
this.name = "luceeDocumentationLocalServer-" & Hash( GetCurrentTemplatePath() );
this.localMode = true;
this.scopeCascading = "small";
this.cwd = GetDirectoryFromPath( GetCurrentTemplatePath() )
this.baseDir = ExpandPath( this.cwd & "../" );
this.mappings[ "/" ] = this.baseDir;
/*
this.mappings[ "/api" ] = this.baseDir & "api";
this.mappings[ "/builders" ] = this.baseDir & "builders";
this.mappings[ "/builds" ] = this.baseDir & "builds";
this.mappings[ "/docs" ] = this.baseDir & "docs";
this.mappings[ "/listener" ] = this.baseDir;
*/
this.assetBundleVersion = 32; // see parent application.cfc
public void function onApplicationStart() {
//_addChangeWatcher();
}
public void function onApplicationEnd() {
//_removeChangeWatcher()
}
public boolean function onRequest( required string requestedTemplate ) output=true {
var path = _getRequestUri();
var logger = new api.build.Logger();
if (path contains ".."){
header statuscode=401;
abort;
}
var importThreads = 4;
// pegdown doesn't work with parallel build, see MarkdownParser.cfc
// see https://luceeserver.atlassian.net/browse/LD-109
var buildThreads = 4;
if ( path.startsWith( "/lucee/admin") ){
request.logger (text="ignoring /lucee/admin request #cgi.script_name#");
return;
} else if ( path.startsWith( "/build_docs/" ) ){
logger.enableFlush(true);
setting requestTimeout=300;
_renderBuildHeader(path);
request.logger("Build: importThreads:#importThreads#, buildThreads: #buildThreads#");
switch (path){
case "/build_docs/all/":
new api.reference.ReferenceImporter(importThreads).importAll();
new api.build.BuildRunner(buildThreads).buildAll(); // threads disabled for now
break;
case "/build_docs/html/":
new api.build.BuildRunner().build(builderName="html", threads=buildThreads);
break;
case "/build_docs/dash/":
new api.build.BuildRunner().build(builderName="dash", threads=buildThreads);
break;
case "/build_docs/import/":
new api.reference.ReferenceImporter(importThreads).importAll();
break;
case "/build_docs/spellCheck/":
new api.spelling.spellChecker().spellCheck();
break;
case "/build_docs/dictionary/":
new api.build.BuildRunner().buildDictionary();
break;
default:
if (listlen(path,"/") gt 1 )
writeOutput("unknown build docs request: #path#");
}
fileAppend(ExpandPath("./performance.log"), "#path# #numberFormat(getTickCount() - request.loggerStart)#ms, "
& "#importThreads# import threads, #buildThreads# build threads, heap #_getMemoryUsage("HEAP")#, non-heap #_getMemoryUsage("NON_HEAP")#, #server.lucee.version# #chr(10)#");
logger.renderLogs();
} else if ( path eq "/assets/js/searchIndex.json" ) {
_renderSearchIndex();
} else if ( path.startsWith( "/assets") or path.startsWith( "/dictionaries" ) ) {
_renderAsset();
} else if ( path.startsWith( "/static" ) ) {
_renderStatic();
} else if ( path.startsWith( "/images" ) ) {
_renderImage();
} else if ( path.startsWith( "/editor.html" ) ) {
_renderCodeEditor();
} else {
lock name="renderPage" timeout="8" type ="Exclusive" throwontimeout="no" {
if ( path.startsWith( "/source" ) ) {
_renderSource();
} else {
_renderPage();
}
}
}
return true;
}
// PRIVATE
private void function _renderPage() {
var pagePath = _getPagePathFromRequest();
var buildRunner = _getBuildRunner();
var docTree = buildRunner.getDocTree();
var page = docTree.getPageByPath( pagePath );
if ( IsNull( page ) ) {
_404(pagePath, "/");
}
WriteOutput( buildRunner.getBuilder( "html" ).renderPage( page, docTree, true ) );
}
private void function _renderSource() {
var isUpdateRequest = (cgi.request_method eq "POST");
var buildRunner = _getBuildRunner(); // no need to scan files
var docTree = buildRunner.getDocTree();
var pagePath = Replace(_getRequestUri(), "/source", "");
var page = docTree.getPageSource(pagePath);
setting showdebugoutput="no";
if (isUpdateRequest){
param name="form.content" default="";
param name="form.properties" default="";
param name="form.url";
var props = {};
if (structCount(page.properties) and len(form.properties) eq 0){
// page had properties
header statuscode=422;
WriteOutput("Properties missing");
abort;
} else if (isJson(form.properties)){
props = deserializeJSON(form.properties);
if (structCount(page.properties) gt 0 and structCount(props) eq 0){
header statuscode=422 statustext="Properties missing";
WriteOutput("Page previously had properties defined");
abort;
}
}
var result = docTree.updatePageSource(pagePath, form.content, props, form.url);
//_resetBuildRunner(); // flag for update
WriteOutput( serializeJSON(result) );
} else {
var pageSource = structNew("linked");
pageSource["file"] = pagePath;
pageSource["content"] = page.content;
pageSource["properties"] = page.properties;
if (structCount(page.properties)){
pageSource["reference"] = {
"categories": docTree.getCategories(),
"pages": docTree.getPageIds()
};
pageSource["propertyTypes"] = page.types;
} else {
structDelete(page, "properties");
}
content type="application/json";
WriteOutput( serializeJSON(pageSource) );
}
}
private void function _renderAsset() {
var assetPath = "/builders/html" & _getRequestUri();
if ( !FileExists( assetPath ) ) {
_404(assetPath, "/");
}
setting showdebugoutput="no";
header name="cache-control" value="no-cache";
content file=assetPath type=_getMimeTypeForAsset( assetPath );
abort;
}
private void function _renderImage() {
var imgPath = "/docs/_images" & mid(_getRequestUri(), len("/images "));
if ( !FileExists( imgPath ) ) {
_404(imgPath, "/");
}
setting showdebugoutput="no";
header name="cache-control" value="no-cache";
content file=imgPath type=_getMimeTypeForAsset( imgPath );
abort;
}
private void function _renderStatic() {
var staticFile = listRest(_getRequestUri(), "/");
if (len(staticFile) eq 0)
staticFile = "index.html";
var staticAssetPath = "/builds/html/" & staticFile ;
if ( !FileExists( staticAssetPath ) ) {
_404(staticAssetPath, "/static/");
}
var pageContent = fileRead(staticAssetPath);
pagecontent = reReplace(pagecontent, '\<a href="\/', '<a href="/static/', 'all');
header name="cache-control" value="no-cache";
setting showdebugoutput="no";
content type=_getMimeTypeForAsset( staticAssetPath );
writeOutput(pagecontent);
abort;
}
private void function _renderCodeEditor() {
var editorPath = "/builders/html/assets/trycf/index.html";
var content = FileRead( editorPath );
setting showdebugoutput="no";
content reset=true;echo(content);abort;
}
private void function _renderSearchIndex() {
var buildRunner = _getBuildRunner();
var docTree = buildRunner.getDocTree(checkFiles = false);
var searchIndex = buildRunner.getBuilder( "html" ).renderSearchIndex( docTree );
header name="cache-control" value="no-cache";
setting showdebugoutput="no";
content type="application/json" reset=true;
writeOutput( searchIndex );
abort;
}
private void function _renderBuildHeader(required string path) {
var opts = structNew("linked");
opts.home = {
title: "Browse Local Documentation",
menu: "Local Docs",
href: "/"
};
opts.static = {
title: "Browse Local Static Docs",
menu: "Local Static",
href: "/static/"
};
opts.prod = {
title: "Browse Prod Docs",
menu: "Prod",
href: "https://docs.lucee.org/"
};
opts.git = {
title: "Lucee Docs Git Repo",
menu: "Git Repo",
href: "https://github.com/lucee/lucee-docs"
};
opts.all = {
title: "Importing references, Exporting Dash and HTML ",
menu: "Build All"
};
opts.html = {
title: "Exporting HTML",
menu: "Build HTML"
};
opts.spellcheck = {
title: "Spellchecking built HTML",
menu: "Spell Check HTML"
};
opts.dictionary = {
title: "Exporting Dictionary",
menu: "Export Dictionary"
};
opts.dash = {
title: "Exporting Dash",
menu: "Build Dash"
};
opts.import = {
Menu: "Import References",
title: "Importing References (tags, functions, options, methods)"
};
opts.admin = {
Title: "Local Lucee Server Admin",
Menu: "Lucee Admin",
href: "/lucee/admin/server.cfm"
}
var textOnly = (url.KeyExists("textlogs") and url.textlogs );
var selectedOption = listLast(arguments.path,"/");
if (textOnly){ // nice for curl --trace http://localhost:4040/build_docs/all/
writeOutput("#chr(10)#Lucee Documentation Builder - #server.lucee.version##chr(10)#");
if (opts.keyExists(selectedOption))
writeOutput("#opts[selectedOption].title##chr(10)##chr(10)#");
setting showdebugoutput="false";
} else {
writeOutput("<h1>Lucee Documentation Builder - #server.lucee.version#</h1>");
writeOutput('<style>.build-menu li { display: inline; list-style-type: none; padding-right: 10px;} ul, ol {padding-left:0;}</style>');
writeOutput('<ul class="build-menu">');
for (var link in opts){
var _link = "/build_docs/#lCase(link)#/";
var _target = "";
if (opts[link].keyExists("href")){
_link = opts[link].href;
var _target = " target='_blank'";
}
writeOutput('<li><a href="#_link#" #_target# title="#htmlEditFormat(opts[link].title)#">#htmlEditFormat(opts[link].menu)#</a></li>');
}
writeOutput('</ul><hr>');
if (opts.keyExists(selectedOption))
writeOutput("<h2>#opts[selectedOption].title#</h2>");
}
}
private string function _getPagePathFromRequest() {
var path = _getRequestUri();
path = ReReplace( path, "\.html$", "" );
if ( path == "/" || path == "/index" ) {
path = "/home";
}
return path;
}
private string function _getRequestUri() {
return request[ "javax.servlet.forward.request_uri" ] ?: "/";
}
private void function _404(required string path, required string baseHref) {
header statuscode=404;
var reqType = listLast(arguments.path, ".");
if (reqType eq "html" or arguments.path does not contain "."){
var buildRunner = _getBuildRunner(checkFiles = false); // no need to scan files
var docTree = buildRunner.getDocTree();
WriteOutput( buildRunner.getBuilder( "html" ).renderFileNotFound( arguments.path, docTree, arguments.baseHref ) );
// add the editor to 404 pages
WriteOutput('<script src="/assets/js/docsEditor.js" type="text/javascript"></script>');
abort;
} else {
content reset="true" type="text/plain";
writeOutput("File not found: #htmlEditFormat(arguments.path)#");
}
abort;
}
private string function _getMimeTypeForAsset( required string filePath ) {
var extension = ListLast( filePath, "." );
switch( extension ){
case "css": return "text/css";
case "js" : return "application/javascript";
case "jpe": case "jpeg": case "jpg": return "image/jpg";
case "png": return "image/png";
case "gif": return "image/gif";
case "svg": return "image/svg+xml";
case "woff": return "font/x-woff";
case "eot": return "application/vnd.ms-fontobject";
case "otf": return "font/otf";
case "ttf": return "application/octet-stream";
case "html": return "text/html";
case "text": return "text/plain";
}
return "application/octet-stream";
}
private any function _getBuildRunner() {
var appKey = "buildRunnerKey";
application.assetBundleVersion = this.assetBundleVersion;
if (structKeyExists(url, "reload") && url.reload eq "true"){
var _start = getTickCount();
inspectTemplates();
//if (structKeyExists(url, "force") && url.force eq "true")
// application[ AppKey ] = new api.build.BuildRunner(); // dev mode
// application[ AppKey ].getDocTree(checkfiles=true); // scans for changes
fileAppend(ExpandPath("./performance.log"), "Docs.reload() #numberFormat(getTickCount() - _start)#ms, "
& " heap #_getMemoryUsage("HEAP")#, non-heap #_getMemoryUsage("NON_HEAP")#, #server.lucee.version# #chr(10)#");
// just restart the whole application
if (structKeyExists(application,AppKey))
ApplicationStop();
location url=ToString(CGI.http_referer ?: cgi.script_name).replaceNoCase("reload=true","") addtoken=false;
}
if ( not application.keyExists( appKey ) ){
request.logger("BuildRunner init");
application.delete( appKey );
var _start = getTickCount();
application[ AppKey ] = new api.build.BuildRunner();
fileAppend(ExpandPath("./performance.log"), "BuildRunner().init() #numberFormat(getTickCount() - _start)#ms, "
& " heap #_getMemoryUsage("HEAP")#, non-heap #_getMemoryUsage("NON_HEAP")#, #server.lucee.version# #chr(10)#");
}
return application[ AppKey ];
}
private void function _addChangeWatcher(){
var password = "lucee-docs";
var admin = new Administrator( "web", password );
admin.updateGatewayEntry(
startupMode="automatic",
id="watchDocumentFilesForChange",
class="",
cfcpath="lucee.extension.gateway.DirectoryWatcher",
// this doesn't work, cfc must be under web-inf dir
// listenerCfcPath="api.build.DocsDirectoryWatcherListener",
// i.e. WEB-INF\lucee-web\components\lucee\extension\gateway\docs
listenerCfcPath="lucee.extension.gateway.Docs.DocsDirectoryWatcherListener",
custom='#{
directory="#expandPath('/docs/')#"
, recurse=true
, interval=5000
, extensions="*.md"
, changeFunction="onAdd"
, addFunction="onAdd"
, deleteFunction="onDelete"
}#',
readOnly=false
);
}
private void function _removeChangeWatcher(){
var password = "lucee-docs";
var admin = new Administrator( "web", password );
admin.removeGatewayEntry(id="watchDocumentFilesForChange");
}
function _getMemoryUsage(type){
var q = getMemoryUsage();
var mem = q.reduce( function(total=0, row, rowNumber, recordset ){
if (arguments.row.type eq type)
return arguments.total + arguments.row.used;
else
return arguments.total;
});
return NumberFormat(mem/(1024*1024)) & " Mb";
}
}