forked from ehmry/syndicated-open
58 lines
1.9 KiB
Nim
58 lines
1.9 KiB
Nim
# SPDX-FileCopyrightText: ☭ 2021 Emery Hemingway
|
|
# SPDX-License-Identifier: Unlicense
|
|
|
|
import std/[asyncdispatch, deques, re, streams, strutils, os, osproc]
|
|
import preserves
|
|
import syndicate, syndicate/capabilities
|
|
import ./protocol
|
|
|
|
proc unixSocketPath: string =
|
|
result = getEnv("SYNDICATE_SOCK")
|
|
if result == "":
|
|
result = getEnv("XDG_RUNTIME_DIR", "/run/user/1000") / "dataspace"
|
|
|
|
proc mintCap: SturdyRef =
|
|
var key: array[16, byte]
|
|
mint(key, "syndicate")
|
|
|
|
bootDataspace("main") do (ds: Ref; turn: var Turn):
|
|
var
|
|
actions: seq[tuple[regex: Regex; cmd: string; args: seq[string]]]
|
|
children: Deque[Process]
|
|
|
|
connectStdio(ds, turn)
|
|
|
|
onPublish(turn, ds, ?UriRunnerConfig[Ref]) do (cfg: seq[Action]):
|
|
actions.setLen 0
|
|
for act in cfg:
|
|
if act.cmd.len < 2:
|
|
stderr.writeLine "ignoring ", act
|
|
else:
|
|
actions.add (re(act.pat, {reIgnoreCase, reStudy}), act.cmd[0], act.cmd[1..act.cmd.high])
|
|
stderr.writeLine "actions updated"
|
|
|
|
connectUnix(turn, unixSocketPath(), mintCap()) do (turn: var Turn; a: Assertion) -> TurnAction:
|
|
let ds = unembed a
|
|
onMessage(turn, ds, ?XdgOpen) do (uris: seq[string]):
|
|
while children.len > 0 and not children.peekFirst.running:
|
|
var child = children.popFirst()
|
|
if child.peekExitCode != 0:
|
|
stderr.writeLine child.errorStream.readAll
|
|
close child
|
|
# TODO check children on a timer?
|
|
for uri in uris:
|
|
var matched: bool
|
|
for act in actions:
|
|
if match(uri, act.regex):
|
|
matched = true
|
|
var args = newSeq[string](act.args.len)
|
|
for i, arg in act.args:
|
|
args[i] = replace(arg, "\\1", uri)
|
|
var child = startProcess(
|
|
command = act.cmd, args = args, options = {})
|
|
children.addLast child
|
|
if not matched:
|
|
stderr.writeLine "no patterns matched for ", uri
|
|
|
|
runForever()
|