syndicated-open/src/uri_runner.nim

42 lines
1.3 KiB
Nim

# SPDX-FileCopyrightText: ☭ 2022 Emery Hemingway
# SPDX-License-Identifier: Unlicense
import std/[asyncdispatch, re]
import preserves, syndicate
import ./protocol
type RegexAction = tuple[regex: Regex; entity: Ref; action: Assertion]
proc rewrite(result: var Assertion; uri: string; regex: Regex) =
proc op(pr: var Assertion) =
if pr.isString:
pr.string = replacef(uri, regex, pr.string)
apply(result, op)
bootDataspace("main") do (root: Ref; turn: var Turn):
var handlers: seq[RegexAction]
connectStdio(root, turn)
onPublish(turn, root, ?ActionHandler[Ref]) do (pat: string; entity: Ref; response: Assertion):
handlers.add (re(pat, {reIgnoreCase, reStudy}), entity, response,)
during(turn, root, ?ListenOn[Ref]) do (ds: Ref):
onMessage(turn, ds, ?XdgOpen) do (uris: seq[string]):
for uri in uris:
var matched: bool
for handler in handlers:
if match(uri, handler.regex):
matched = true
var response = handler.action
rewrite(response, uri, handler.regex)
message(turn, handler.entity, response)
if not matched:
stderr.writeLine "no actions matched for ", uri
do:
# The Syndicate server retracts all assertions when
# the config is rewritten.
handlers.setLen 0
runForever()