syndicated-open/src/uri_runner.nim

42 lines
1.3 KiB
Nim
Raw Normal View History

# SPDX-FileCopyrightText: ☭ 2022 Emery Hemingway
2022-02-26 23:39:22 +00:00
# SPDX-License-Identifier: Unlicense
2022-05-19 16:58:47 +00:00
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)
2022-02-26 23:39:22 +00:00
bootDataspace("main") do (root: Ref; turn: var Turn):
var handlers: seq[RegexAction]
2022-02-26 23:39:22 +00:00
connectStdio(root, turn)
2022-02-26 23:39:22 +00:00
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):
2022-02-26 23:39:22 +00:00
onMessage(turn, ds, ?XdgOpen) do (uris: seq[string]):
for uri in uris:
var matched: bool
for handler in handlers:
if match(uri, handler.regex):
2022-02-26 23:39:22 +00:00
matched = true
var response = handler.action
rewrite(response, uri, handler.regex)
message(turn, handler.entity, response)
2022-02-26 23:39:22 +00:00
if not matched:
stderr.writeLine "no actions matched for ", uri
2022-04-23 23:32:43 +00:00
do:
# The Syndicate server retracts all assertions when
# the config is rewritten.
handlers.setLen 0
2022-02-26 23:39:22 +00:00
runForever()