2023-05-06 19:05:08 +00:00
|
|
|
# SPDX-FileCopyrightText: ☭ Emery Hemingway
|
2022-02-26 23:39:22 +00:00
|
|
|
# SPDX-License-Identifier: Unlicense
|
|
|
|
|
2023-06-30 14:26:22 +00:00
|
|
|
import std/[re, tables, uri]
|
2023-10-10 08:04:59 +00:00
|
|
|
import preserves, syndicate, syndicate/relays, syndicate/patterns
|
2023-06-30 14:26:22 +00:00
|
|
|
import ./protocol, ./common
|
2022-06-25 18:53:51 +00:00
|
|
|
|
2023-05-18 09:46:17 +00:00
|
|
|
# importing std/re doesn't actually link against PCRE
|
|
|
|
{.passC: staticExec("pkg-config --cflags libpcre").}
|
|
|
|
{.passL: staticExec("pkg-config --libs libpcre").}
|
|
|
|
|
2023-10-10 08:04:59 +00:00
|
|
|
type RegexAction = tuple[regex: Regex, entity: Cap, action: Assertion]
|
2022-06-25 18:53:51 +00:00
|
|
|
|
2023-10-10 08:04:59 +00:00
|
|
|
proc rewrite(result: var Assertion; uri: string; regex: Regex) {.gcsafe.} =
|
|
|
|
proc op(pr: var Assertion) {.gcsafe.} =
|
2022-06-25 18:53:51 +00:00
|
|
|
if pr.isString:
|
|
|
|
pr.string = replacef(uri, regex, pr.string)
|
|
|
|
apply(result, op)
|
2022-02-26 23:39:22 +00:00
|
|
|
|
2023-10-10 08:04:59 +00:00
|
|
|
runActor("main") do (root: Cap; turn: var Turn):
|
2023-10-21 17:52:59 +00:00
|
|
|
connectStdio(turn, root)
|
2023-10-10 08:04:59 +00:00
|
|
|
let handlers = newTable[Handle, RegexAction]()
|
|
|
|
during(turn, root, ?UriRunnerConfig) do (handlerspace: Cap, urispace: Cap):
|
2023-05-18 09:46:17 +00:00
|
|
|
|
|
|
|
during(turn, handlerspace, dropType(ActionHandler)) do:
|
2022-02-26 23:39:22 +00:00
|
|
|
|
2023-10-10 08:04:59 +00:00
|
|
|
during(turn, handlerspace, ?ActionHandler) do (pat: string; entity: Cap; act: Assertion):
|
2023-05-18 09:46:17 +00:00
|
|
|
# `duringHandle` is a symbol exposed by the `during` macro
|
|
|
|
handlers[duringHandle] = (re(pat, {reIgnoreCase, reStudy}), entity, act,)
|
|
|
|
do:
|
|
|
|
del(handlers, duringHandle)
|
2022-06-25 18:53:51 +00:00
|
|
|
|
2023-06-30 14:26:22 +00:00
|
|
|
onMessage(turn, urispace, Open ? {0:grab()}) do (u: uri.Uri):
|
|
|
|
let uri = $u
|
2023-05-18 09:46:17 +00:00
|
|
|
assert len(handlers) > 0
|
|
|
|
var matched = false
|
|
|
|
for handler in handlers.values:
|
2022-06-25 18:53:51 +00:00
|
|
|
if match(uri, handler.regex):
|
2022-02-26 23:39:22 +00:00
|
|
|
matched = true
|
2023-05-18 09:46:17 +00:00
|
|
|
var action = handler.action
|
|
|
|
try:
|
|
|
|
rewrite(action, uri, handler.regex)
|
|
|
|
message(turn, handler.entity, action)
|
|
|
|
except CatchableError:
|
|
|
|
stderr.writeLine "rewrite failed on ", action
|
2022-02-26 23:39:22 +00:00
|
|
|
if not matched:
|
2022-03-19 00:22:31 +00:00
|
|
|
stderr.writeLine "no actions matched for ", uri
|
2023-06-23 15:23:57 +00:00
|
|
|
do:
|
|
|
|
clear(handlers)
|