-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoJobHTTPd.yaml
More file actions
871 lines (819 loc) · 34.8 KB
/
oJobHTTPd.yaml
File metadata and controls
871 lines (819 loc) · 34.8 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
# Copyright 2025 Nuno Aguiar
jobs:
# Prepares a HTTP server
#
# ------------------------
- name : HTTP Start Server
typeArgs:
noLog: false
shortcut:
name : httpdStart
keyArg: port
args :
hs : hs
keystore : keystore
pass : pass
host : host
uriPrefix: uriPrefix
cp : cp
mapLibs : mapLibs
help :
text : Provides and starts a HTTP server.
expects:
- name: port
desc: (Number) The port where the server should be made available (default is 8091)
- name: hs
desc: (HTTPServer) A HTTPServer to use (is not provided one will be created)
- name: keystore
desc: (String) Optionally to create a https server provide a keystore file
- name: pass
desc: (String) The password for the keystore of a https server
- name: host
desc: (String) Optionally the interface where the server should be listening (default is all)
- name: cp
desc: (String) Optionally providing the classpath URL to include the keystore file
- name: uriPrefix
desc: (String) Optionally a URI prefix to be applied to all routes
- name: mapLibs
desc: (boolean) Map also internal libs (e.g. jquery, css, etc...)
exec : | #js
ow.loadServer()
var ks
if (isUnDef(global.__ojobHttp)) global.__ojobHttp = {}
if (isUnDef(global.__ojobRoutes)) global.__ojobRoutes = {}
if (isUnDef(global.__ojobPreRoutes)) global.__ojobPreRoutes = {}
if (isUnDef(args.port)) args.port = 8091; else args.port = Number(args.port)
if (isUnDef(args.uriPrefix) && isDef(__flags.HTTPD_PREFIX)) {
if (isMap(__flags.HTTPD_PREFIX)) {
args.uriPrefix = _$( __flags.HTTPD_PREFIX[String(args.port)]).default(
_$( __flags.HTTPD_PREFIX[args.port]).default(
_$( __flags.HTTPD_PREFIX["0"]).default(
_$( __flags.HTTPD_PREFIX[0]).default(__))))
} else {
args.uriPrefix = __flags.HTTPD_PREFIX
}
}
if (isUnDef(args.uriPrefix)) args.uriPrefix = __
if (isUnDef(args.cp) && isDef(args.keystore) && !isNull(java.io.File(args.keystore).getParent())) args.cp = java.io.File(args.keystore).getParent().toString()
if (isDef(args.cp)) af.externalAddClasspath(args.cp)
if (isDef(args.keystore)) ks = args.keystore
args.mapLibs = _$(args.mapLibs).isBoolean().default(false)
if (isUnDef(global.__ojobHttp[args.port])) global.__ojobHttp[args.port] = (isDef(args.hs) ? args.hs : ow.server.httpd.start(args.port, args.host, ks, args.pass))
if (isUnDef(global.__ojobPreRoutes[args.port])) global.__ojobPreRoutes[args.port] = ""
if (isUnDef(global.__ojobHttpUriPrefix)) global.__ojobHttpUriPrefix = {}
global.__ojobHttpUriPrefix[args.port] = args.uriPrefix
if (isUnDef(global.__ojobRoutes[args.port])) {
if (args.mapLibs) {
global.__ojobRoutes[args.port] = ow.server.httpd.mapRoutesWithLibs(global.__ojobHttp[args.port], {})
} else {
global.__ojobRoutes[args.port] = {}
}
}
# Applies a HTTP service definition
#
# -------------------------
- name : HTTP Apply Service
exec : | #js
if (isUnDef(args.port)) args.port = 8091; else args.port = Number(args.port)
ow.server.httpd.route(global.__ojobHttp[args.port], global.__ojobRoutes[args.port], function(r) { return global.__ojobHttp[args.port].reply("", "", 401, {}); })
log("READY [" + args.port + "]")
# Stopping the HTTP server
#
# ----------------------
- name: HTTP Stop Server
type: shutdown
typeArgs:
noLog: false
shortcut:
name : httpdStop
keyArg: port
args : {}
help:
text : Sets a shutdown job for the server. If using sequential do ensure that the job 'HTTP Start Server' gets executed first.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
deps:
- HTTP Start Server
exec: | #js
if (isUnDef(args.port)) args.port = 8091; else args.port = Number(args.port)
ow.server.httpd.stop(global.__ojobHttp[args.port])
delete global.__ojobHttp[args.port]
delete global.__ojobHttpUriPrefix[args.port]
delete global.__ojobRoutes[args.port]
log("STOPPED [" + args.port + "]")
# ------------------------
- name : HTTP Default Auth
deps :
- HTTP Start Server
typeArgs:
noLog: false
shortcut:
name : httpdDefaultAuth
keyArg: port
args :
execAuth: execAuth
help :
text : Provides a default authentication function for all routes on a given port.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: execAuth
desc: (Function) The authentication function. Receives a request map and a server object
exec : | #js
args.port = _$(args.port).isNumber().default(8091)
args.execAuth = _$(args.execAuth).isString().$_()
global.__ojobPreRoutes[args.port] = args.execAuth
# Defines a HTTP service
#
# -------------------
- name : HTTP Service
deps :
- HTTP Start Server
to : HTTP Apply Service
typeArgs:
noLog: false
shortcut:
name : httpdService
keyArg: port
args :
uri : uri
execURI : execURI
audit : audit
auditTemplate: auditTemplate
error : error
execPre : execPre
help :
text: Provides a HTTP service definition. If using sequential jobs do ensure that the job 'HTTP Start Server' gets executed first.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP service will be available.
- name: execURI
desc: (Function) The URI execution function. Receives a request map and a server object.
- name: audit
desc: (Boolean) Turns request audit logging on (default true)
- name: auditTemplate
desc: (String) Provide an audit logging template based on the request argument.
- name: error
desc: (Boolean) If true will return the error in case of exception.
- name: execPre
desc: (String) A pre-execution code include to execURI useful for authentication
exec : | #js
args.port = _$(args.port).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/")
args.audit = _$(args.audit).default(true)
args.execPre = _$(args.execPre).isString().default(__)
args.auditTemplate = _$(args.auditTemplate).default("AUDIT HTTP | {{method}} {{uri}} {{reply.status}} {{{reply.mimetype}}} ({{header.remote-addr}}; {{header.user-agent}})")
if (isUnDef(args.execPre) && isDef(global.__ojobPreRoutes[args.port])) {
args.execPre = global.__ojobPreRoutes[args.port]
} else {
args.execPre = ""
}
var fn = __
if (args.audit) {
fn = (req, reply) => {
var data = merge(req, {
reply: {
status : reply.status,
mimetype: reply.mimetype
}
})
try {
tlog(args.auditTemplate, data)
} catch(e) {
logErr("Error on auditing access: " + String(e))
}
}
}
global.__ojobRoutes[args.port][args.uri] = function(r) {
try {
var res = (new Function("var request = arguments[0]; var server = global.__ojobHttp[" + args.port + "]; var port = " + String(args.port) + "; var uri = '" + args.uri + "'; " + args.execPre + "; " + args.execURI))(r)
if (!isMap(res)) res = ow.server.httpd.reply(res, void 0, void 0, {})
fn(r, res)
return res
} catch(e) {
if (args.error) {
return { data: String(e), mimetype: "text/plain", status: 500, header: {} }
}
}
}
# -------------------
- name : HTTP Default
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdDefault
keyArg: port
args :
uri : uri
code : code
audit : audit
auditTemplate: auditTemplate
error : error
help :
text : Provides a HTTP default handler.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP default response will be available (defaults to /)
- name: code
desc: (Number) The default HTTP status code to reply (default is 401)
- name: audit
desc: (Boolean) Turns request audit logging on (default true)
- name: auditTemplate
desc: (String) Provide an audit logging template based on the request argument.
- name: error
desc: (Boolean) If true will return the error in case of exception.
exec : | #js
args.code = _$(args.code, "code").isNumber().default(401)
args.uri = _$(args.uri, "uri").isString().default("/")
args.execURI = "return ow.server.httpd.reply(\"\", " + args.code + ", __, {});"
# --------------------
- name : HTTP Redirect
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdRedirect
keyArg: port
args :
uri : uri
targetURI : targetURI
code : code
audit : audit
auditTemplate: auditTemplate
error : error
help :
text : Provides a HTTP default handler.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP default response will be available (defaults to /)
- name: code
desc: (Number) The default HTTP status code to reply (default is 401)
- name: audit
desc: (Boolean) Turns request audit logging on (default true)
- name: auditTemplate
desc: (String) Provide an audit logging template based on the request argument.
- name: error
desc: (Boolean) If true will return the error in case of exception.
- name: targetURI
desc: (String) The target URI to redirect to
exec : | #js
args.code = _$(args.code, "code").isNumber().default(401)
args.uri = _$(args.uri, "uri").isString().default("/")
args.targetURI = _$(args.targetURI, "targetURI").isString().$_("You need to provide a target URI.")
args.execURI = "return ow.server.httpd.replyRedirect(server, \"" + args.targetURI + "\", {});"
# ------------------
- name : HTTP Upload
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdUpload
keyArg: port
args :
uri : uri
path : path
execURI : execURI
audit : audit
auditTemplate: auditTemplate
error : error
help :
text : Provides a HTTP upload handler.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP default response will be available (defaults to /upload)
- name: path
desc: (String) The local path where uploaded files will be saved
- name: execURI
desc: (Function) The URI execution function. Receives a request map and a server object. If doesn't return any value it will proceed to save the file on the corresponding path after code execution.
- name: audit
desc: (Boolean) Turns request audit logging on (default true)
- name: auditTemplate
desc: (String) Provide an audit logging template based on the request argument.
- name: error
desc: (Boolean) If true will return the error in case of exception.
args :
eURI: |
if (isDef(request.params) && isDef(request.params.data) && request.method == "POST") {
log("Received file '" + request.params.data + "'...")
io.cp(request.files.data, '{{{path}}}/' + request.params.data)
return "ok"
} else {
return server.replyOKHTML("<html><body><form action=\"" + request.uri + "\" enctype=\"multipart/form-data\" method=\"POST\"><input type=\"file\" name=\"data\" value=\"data\" id=\"data\"/><input type=\"submit\" value=\"submit\"/></form></body></html>")
}
exec: | #js
args.path = _$(args.path, "path").default(".")
args.uri = _$(args.uri).isString().default("/upload")
io.mkdir(args.path)
args.execURI = (isDef(args.execURI) ? args.execURI : "") + "\n" + templify(args.eURI, { path: args.path })
# -------------------
- name : HTTP Healthz
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdHealthz
keyArg: port
args :
uri : uri
path : path
healthz : healthz
openmetrics: openmetrics
help :
text: Adds a healthz URI
expects:
- name: port
desc: The port of the HTTP Start Server (default to 8091)
- name: uri
desc: The uri to use (default /healthz)
- name: healthz
desc: A custom function to return the /healthz result (defaults to ow.metrics.getAll with status 200 or "error" with status 500 if an exception is thrown)
- name: openmetrics
desc: If openmetrics = true the output will be in openmetrics/prometheus instead of json
exec: | #js
ow.loadMetrics()
args.port = _$(args.port).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/healthz")
var s1 = " try { return ow.server.httpd.reply(ow.metrics.getAll()); } catch(e) { return ow.server.httpd.reply(\"error\", 500, void 0, {}); } "
var s2 = " try { return ow.metrics.fromObj2OpenMetrics(ow.metrics.getAll()); } catch(e) { return ow.server.httpd.reply(\"error\", 500, void 0, {}); } "
args.healthz = _$(args.healthz).isString().default(args.openmetrics ? s2 : s1)
args.execURI = args.healthz
# ------------------
- name : HTTP Metrics
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdMetrics
keyArg: port
args :
uri : uri
metrics: metrics
prefix : prefix
helpmap: helpmap
help :
text: Adds a metrics URI with a OpenMetrics/Prometheus output
expects:
- name: port
desc: The port of the HTTP Start Server (default to 8091)
- name: uri
desc: The uri to use (default /metrics)
- name: metrics
desc: A custom function to return the /metrics result (defaults to ow.metrics.getAll with status 200 or "error" with status 500 if an exception is thrown).
- name: prefix
desc: OpenMetrics/Prometheus metrics' name prefix
- name: helpmap
desc: OpenMetrics/Prometheus metrics' help map (see help ow.metrics.fromObj2OpenMetrics)
exec : | #js
ow.loadMetrics()
args.port = _$(args.port).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/metrics")
args.metrics = _$(args.metrics).isString().default("try { var rrr = ow.server.httpd.reply(ow.metrics.fromObj2OpenMetrics((isDef(request.params.s) ? ow.metrics.getSome(request.params.s.split(\",\")) : ow.metrics.getAll()), " + stringify(args.prefix) + ", now(), " + stringify(args.helpmap,__,'') + ")); rrr.data = String(rrr.data); return rrr; } catch(e) { logErr(e); return { data: \"error\", status: 500, mimetype: \"text/plain\" }; } ")
args.execURI = args.metrics
# ----------------------
- name : HTTP Add Metric
typeArgs:
noLog: false
shortcut:
name : httpdAddMetric
keyArg: metric
args :
fn: fn
help :
text : Add a metric to the current daemon execution
expects:
- name: metric
desc: Metric name
- name: fn
desc: Metric function code returning a map
exec: | #js
_$(args.metric, "metric").$_()
_$(args.fn, "fn").$_()
ow.loadMetrics()
ow.metrics.add(args.metric, new Function(args.fn))
# Defines an inline markdown response
#
# --------------------
- name : HTTP markdown
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdMD
keyArg: port
args :
uri : uri
md : md
help :
text: Adds a markdown URI
expects:
- name: port
desc: The port of the HTTP Start Server (default to 8091)
- name: uri
desc: The uri to use (default /metrics)
- name: md
desc: The markdown content to be returned
exec : | #js
args.port = _$(Number(args.port)).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/")
args.md = _$(args.md).isString().default("You need to provide a markdown content.")
args.execURI = "try { return server.replyOKHTML(ow.template.parseMD2HTML(`" + args.md.replace(/\`/g, "\\`") + "`, true)) } catch(e) { logErr(e); return { data: \"error\", status: 500, mimetype: \"text/plain\" } }"
# Defines a classic HTTP file browse
#
# ---------------------------------
- name : HTTP Classical File Browse
deps :
- HTTP Start Server
typeArgs:
noLog: false
shortcut:
name : httpdClassicFileBrowse
keyArg: port
args :
uri : uri
path: path
help :
text : Provides a classical HTTP file browse definition.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP File Browse will be available.
- name: path
desc: (String) The canonical path (real path) to the folder that contains the file to be browsed.
exec: | #js
args.port = _$(Number(args.port)).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/")
_$(args.path).isString().$_("You need to provide a path.")
global.__ojobHttp[args.port].addFileBrowse(args.uri, args.path)
# Defines a HTTP file browse
#
# -----------------------
- name : HTTP File Browse
deps :
- HTTP Start Server
to : HTTP Service
typeArgs:
noLog: false
shortcut:
name : httpdFileBrowse
keyArg: port
args :
uri : uri
path : path
browse : browse
default : default
logo : logo
restrict : restrict
incURI : incURI
sortTab : sortTab
help :
text : Provides a HTTP file browse definition.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the HTTP File Browse will be available.
- name: path
desc: (String) The canonical path (real path) to the folder that contains the file to be browsed.
- name: browse
desc: (String) If "false" no browsing interface is included.
- name: default
desc: (String) The markdown or html filename to consider default (e.g. index.md)
- name: logo
desc: (String) The logo to include on the top right corner
- name: restrict
desc: (String) A comma separated list of regular expressions to restrict the access to the files
- name: incURI
desc: (Boolean) If true includes the URI in the breadcrumbs
- name: sortTab
desc: (Boolean) If true includes the table sorting script (OpenAF >= 20250402)
check:
in:
port : toNumber.isNumber.default(8091)
uri : isString.default("/")
path : isString.default(".")
browse : toBoolean.isBoolean.default(true)
default : isString.default(__)
logo : isString.default("/fonts/openaf_small.png")
restrict : default(__)
incURI : toBoolean.isBoolean.default(false)
sortTab : toBoolean.isBoolean.default(false)
args :
execURI : | #js
var shouldBrowse = global.__MHTTPD[String(port) + uri].BROWSE
var path = global.__MHTTPD[String(port) + uri].PATH
var tmplb = global.__MHTTPD[String(port) + uri].TMPLB
var tmplh = global.__MHTTPD[String(port) + uri].TMPLH
var fdefault = global.__MHTTPD[String(port) + uri].DEFAULT
var restrict = global.__MHTTPD[String(port) + uri].RESTRICT
var incURI = global.__MHTTPD[String(port) + uri].INCURI
var sortTab = global.__MHTTPD[String(port) + uri].SORTTAB
var uriPrefix = _$(global.__ojobHttpUriPrefix[String(port)], "__ojobHttpUriPrefix1").default(_$(global.__ojobHttpUriPrefix[port], "__ojobHttpUriPrefix2").default(""))
var prefixURL = aURL => {
aURL = _$(aURL).default("")
if (aURL == "") return aURL
aURL = String(aURL)
if ((/^[a-z]+:/i).test(aURL) || aURL.startsWith("//")) return aURL
if (!aURL.startsWith("/")) return aURL
return (uriPrefix + (uriPrefix.length > 0 ? "/" : "") + aURL.replace(/^\/+/, "")).replace(/\/+/g, "/")
}
var content = ""
var puri = String(request.uri).replace(new RegExp("^" + uri), (uri == "/" ? "" : "/")).replace(/\/+/g, "/")
var furi = String((new java.io.File(new java.io.File(String((new java.io.File(path + "/" + puri)).getCanonicalFile()).replace(/\\+/g, "/")))))
var finfo
try {
finfo = io.fileInfo(furi)
} catch(e) {
return server.replyOKHTML("")
}
if (finfo.isDirectory) {
try {
if (!request.originalURI.endsWith("/")) {
var redirectURI = String(_$(request.original).default(request.uri))
var q = isMap(request.params) && Object.keys(request.params).length > 0 && Object.keys(request.params).filter(k => request.params[k] != null).length > 0
? "?" + Object.keys(request.params).filter(k => request.params[k] != null).map(k => encodeURIComponent(k) + "=" + encodeURIComponent(request.params[k])).join("&")
: ""
print("Redirecting to " + redirectURI + (!redirectURI.endsWith("/") ? "/" : "") + q)
return ow.server.httpd.replyRedirect(server, redirectURI + (!redirectURI.endsWith("/") ? "/" : "") + q, {})
}
} catch(eee) { $err(eee) }
if (!puri.endsWith("/")) puri += "/"
if (isDef(fdefault) && io.fileExists(furi + "/" + fdefault)) {
return (fdefault.endsWith(".md") ?
ow.server.httpd.replyFileMD(server, path, uri, request.uri + "/" + fdefault) : ow.server.httpd.replyFile(server, path, uri, request.uri + "/" + fdefault))
} else {
if (shouldBrowse) {
content += tmplh({ puri: (!puri.startsWith("/") ? "/" + puri : puri) })
content += "| | Filename | Last modified | Size | Size in bytes |\n"
content += "|---|----------|:-------------:|-----:|--------------:|\n"
if (puri != "/" && puri != "")
content += "| <span style=\"color: #a0a0a0;\">↖</span> | __[..](<../>)__ | | |\n"
var theList = $from(io.listFiles(furi).files).sort("-isDirectory", "filename").select(f => {
//if (f.filename.endsWith("/")) f.filename = f.filename.substr(0, f.filename.length-1)
return merge(f, {
fLastModified: ow.format.fromDate(new Date(f.lastModified), 'yyyy-MM-dd HH:mm:ss'),
fSize : ow.format.toBytesAbbreviation(f.size),
puri : puri
})
})
if (isDef(restrict)) {
if (isString(restrict)) restrict = [ restrict ]
lst = lst.filter(f => restrict.reduce((aP, aC) => (aP && !(new RegExp(aC)).test(f.filepath)), true))
}
content += tmplb(theList)
}
}
} else {
if (puri.endsWith("/")) puri = puri.replace(/\/+$/, "")
if (request.params.raw == "true") {
return ow.server.httpd.replyFile(server, path, uri, request.uri)
} else {
var ext = String(furi).replace(/^.*\./, "")
var _downloadcode = `<span><script>
function downloadText(aFile) {
var selectedText = document.querySelectorAll("pre")[0].innerText
const blob = new Blob([selectedText], { type: "text/plain" })
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = aFile
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
</script></span>`
var fn = () => ow.server.httpd.replyFileMD(server, path, uri, request.uri)
var fnLang = lang => {
ow.loadTemplate()
var _displayURI = uri.replace(/\/$/, "")
_displayURI = _displayURI.replace(new RegExp("^" + uri), "")
_displayURI += puri
return server.reply( ow.template.parseMD2HTML("## " + $t("{{{ojh-buildBreadcrumbs '" + _displayURI + "' '" + uri + "' " + incURI + " false}}}") + "<span onclick=\"history.back()\" onmouseout=\"this.style.textDecoration='none';\" onmouseover=\"this.style.textDecoration='underline';\" style=\"padding-left: 1em; float: right; text-decoration: none; cursor: pointer;\"><a href=\"javascript:history.back()\">←</a></span><span onclick=\"downloadText('" + puri.replace(/\/?$/,"").substr(puri.replace(/\/?$/,"").lastIndexOf("/")+1) + "')\" onmouseout=\"this.style.textDecoration='none';\" onmouseover=\"this.style.textDecoration='underline';\" style=\"padding-left: 1em; float: right; text-decoration: none; cursor: pointer;\"><a href=\"javascript:downloadText('" + puri.replace(/\/?$/,"").substr(puri.replace(/\/?$/,"").lastIndexOf("/")+1) + "')\">↓</a></span>\n\n```" + lang + "\n" + io.readFileString(furi) + "\n```\n" + _downloadcode, true, true), "text/html", 200)
}
switch(ext) {
case "md" : return fn()
case "yml" :
case "yaml": return fnLang("yaml")
case "sh" : return fnLang("sh")
case "css" : return fnLang("css")
case "sh" : return fnLang("sh")
case "js" : return fnLang("js")
case "java": return fnLang("java")
case "py" : return fnLang("python")
case "toml": return fnLang("toml")
case "hbs" : return fnLang("handlebars")
case "json":
if (request.params.parse == "false") {
return fnLang("json")
} else {
var _d = io.readFileJSON(furi)
if (isMap(_d) || isArray(_d))
return ow.server.httpd.replyJSMap(server, _d)
else
return fn()
}
case "adoc":
if (isDef(getOPackPath("Asciidoc"))) {
loadLib("asciidoc.js")
return ow.server.httpd.replyAsciidoc(server, path, uri, request.uri)
}
default:
return ow.server.httpd.replyFile(server, path, uri, request.uri)
}
}
}
if (sortTab) content += "<script src=\"" + prefixURL("/js/mdtablesort.js") + "\"></script>\n"
if (shouldBrowse)
return server.replyOKHTML(ow.template.parseMD2HTML(content, true))
else
return server.replyOKHTML("")
exec : | #js
ow.loadTemplate(); ow.loadFormat()
ow.template.addHelper("encodeURI", encodeURI)
args.uri = _$(args.uri).isString().default("/")
args.path = _$(args.path).isString().default(".")
var uriPrefix = _$(global.__ojobHttpUriPrefix[String(args.port)], "__ojobHttpUriPrefix1").default(_$(global.__ojobHttpUriPrefix[args.port], "__ojobHttpUriPrefix2").default(""))
var prefixURL = aURL => {
aURL = _$(aURL).default("")
if (aURL == "") return aURL
aURL = String(aURL)
if ((/^[a-z]+:/i).test(aURL) || aURL.startsWith("//")) return aURL
if (!aURL.startsWith("/")) return aURL
return (uriPrefix + (uriPrefix.length > 0 ? "/" : "") + aURL.replace(/^\/+/, "")).replace(/\/+/g, "/")
}
ow.template.addHelper("escapeMDTable", str => str.replace(/\|/g, "\\|"))
ow.template.addHelper("ojh-buildBreadcrumbs", (path, _uri, _incURI, _isDir) => {
// Remove any leading or trailing slashes and split into segments.
const trimmedPath = path.replace(/^\/|\/$/g, '')
const segments = trimmedPath ? trimmedPath.split('/') : []
const relDir = aDepth => (aDepth <= 0 ? "./" : "../".repeat(aDepth))
const baseDepth = Math.max(0, segments.length - (_isDir ? 0 : 1))
const rootURI = relDir(baseDepth)
// Start with the clickable root.
let html = ""
if (!_incURI)
html = `<a href="${rootURI}" title="Navigate to root"> / </a>`
else
html = `<a href="${rootURI}" title="Navigate to root"> ${_uri.replace(/^\//, "/ ")} / </a>`
segments.forEach((segment, index) => {
// Add separator before each segment.
if (index > 0) html += ' / '
// If it's the last segment (current location), show as plain text.
if (index === segments.length - 1) {
html += `<span>${segment}</span>`
} else {
const targetURI = relDir(Math.max(0, baseDepth - index - 1))
html += `<a href="${targetURI}" title="Navigate to ${segment}">${segment}</a>`
}
})
return html
})
args.logo = prefixURL(_$(args.logo, "logo").isString().default("/fonts/openaf_small.png"))
var temph = _$(args.templateHead).isString().default("## {{{ojh-buildBreadcrumbs puri '" + args.uri + "' " + args.incURI + " true}}}<img style=\"padding-left: 1em;\" align=\"right\" src=\"" + args.logo + "\">\n")
var templ = _$(args.template).isString().default("{{#each this}}| {{#if isDirectory}}<span style=\"color: #a0a0a0;\">↘</span>{{else}}<a href=\"{{encodeURI filename}}?raw=true\" download=\"{{encodeURI filename}}\">↓</a>{{/if}} | {{#if isDirectory}}__[{{escapeMDTable filename}}](<{{encodeURI filename}}/>)__ | {{fLastModified}} | | {{else}} [{{escapeMDTable filename}}](<{{encodeURI filename}}>) | {{fLastModified}} {{/if}} | {{fSize}} | {{size}} | \n{{/each}}")
global.__MHTTPD = _$(global.__MHTTPD).isMap().default({})
global.__MHTTPD[String(args.port) + args.uri] = {
BROWSE : args.browse,
PATH : String( (new java.io.File( args.path )).getCanonicalPath() ),
TMPLB : ow.template.execCompiled(ow.template.compile(templ)),
TMPLH : ow.template.execCompiled(ow.template.compile(temph)),
INCURI : args.incURI,
URI : args.uri,
DEFAULT : _$(args.default).isString().default(__),
RESTRICT: args.restrict,
SORTTAB : args.sortTab
}
# Defines a HTTP SSE (Server-Sent Events) service
#
# -----------------------
- name : HTTP SSE Service
deps :
- HTTP Start Server
to : HTTP Apply Service
typeArgs:
noLog: false
shortcut:
name : httpdSSE
keyArg: port
args :
uri : uri
execSSE : execSSE
audit : audit
auditTemplate: auditTemplate
error : error
execPre : execPre
help :
text: Provides a Server-Sent Events (SSE) streaming endpoint. If using sequential jobs do ensure that the job 'HTTP Start Server' gets executed first.
expects:
- name: port
desc: (Number) The port where the server was made available (default is 8091)
- name: uri
desc: (String) The URI where the SSE endpoint will be available.
- name: execSSE
desc: (Function) The SSE execution function. Receives (writer, request) where writer has write(event, data) and close() methods.
- name: audit
desc: (Boolean) Turns request audit logging on (default true)
- name: auditTemplate
desc: (String) Provide an audit logging template based on the request argument.
- name: error
desc: (Boolean) If true will return the error in case of exception.
- name: execPre
desc: (String) A pre-execution code include to execSSE useful for authentication
exec : | #js
args.port = _$(args.port).isNumber().default(8091)
args.uri = _$(args.uri).isString().default("/sse")
args.audit = _$(args.audit).default(true)
args.execPre = _$(args.execPre).isString().default(__)
args.auditTemplate = _$(args.auditTemplate).default("AUDIT SSE | {{method}} {{uri}} ({{header.remote-addr}}; {{header.user-agent}})")
if (isUnDef(args.execPre) && isDef(global.__ojobPreRoutes[args.port])) {
args.execPre = global.__ojobPreRoutes[args.port]
} else {
args.execPre = ""
}
var fn = __
if (args.audit) {
fn = (req, reply) => {
var data = merge(req, {
reply: {
status : reply.status,
mimetype: reply.mimetype
}
})
try {
tlog(args.auditTemplate, data)
} catch(e) {
logErr("Error on auditing SSE access: " + String(e))
}
}
}
global.__ojobRoutes[args.port][args.uri] = function(r) {
try {
var pis = new java.io.PipedInputStream()
var pos = new java.io.PipedOutputStream(pis)
var _closed = false
var writer = {
write: function(event, data) {
if (_closed) return
var msg = "event: " + event + "\n"
msg += "data: " + JSON.stringify(data) + "\n\n"
pos.write(af.fromString2Bytes(msg))
pos.flush()
},
close: function() {
if (_closed) return
_closed = true
try { pos.close() } catch(e) {}
}
}
$doV(function() {
try {
(new Function("var writer = arguments[0]; var request = arguments[1]; var server = global.__ojobHttp[" + args.port + "]; var port = " + String(args.port) + "; var uri = '" + args.uri + "'; " + args.execPre + "; " + args.execSSE))(writer, r)
} catch(e) {
writer.write("error", { message: String(e) })
if (args.error) logErr("SSE error: " + String(e))
} finally {
writer.close()
}
})
var res = {
status : 200,
mimetype: "text/event-stream",
stream : pis,
header : {
"Cache-Control" : "no-cache, no-transform",
"Connection" : "keep-alive",
"Content-Encoding" : "identity",
"X-Accel-Buffering": "no"
}
}
if (fn) fn(r, res)
return res
} catch(e) {
if (args.error) {
return { data: String(e), mimetype: "text/plain", status: 500, header: {} }
}
}
}