syndicated-open/src/uri_runner.nim

50 lines
1.8 KiB
Nim

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