Make calls live, default config relays to ntfy.sh

This commit is contained in:
Christopher Vagnetoft
2026-01-17 17:23:38 +01:00
parent b1690a10d2
commit 8b80f25f79

View File

@@ -24,6 +24,12 @@ class NtfiDaemon
private array $channels = [];
/**
* Set the configuration file to use
*
* @param string|null $filename
* @return self
*/
public function setConfigFile(?string $filename): self
{
if ($filename && !file_exists($filename)) {
@@ -33,6 +39,11 @@ class NtfiDaemon
return $this;
}
/**
* Read the configuration, and/or return with defaults.
*
* @return array
*/
private function readConfig(): array
{
$config = [
@@ -58,6 +69,11 @@ class NtfiDaemon
return $config;
}
/**
* Start the daemon after trying to read the config.
*
* @return self
*/
public function start(): self
{
$config = $this->readConfig();
@@ -74,6 +90,12 @@ class NtfiDaemon
return $this;
}
/**
* Setup the HTTP server
*
* @param string $listen
* @return void
*/
private function setupHttp(string $listen): void
{
$this->httpServer = new HttpServer(
@@ -83,6 +105,12 @@ class NtfiDaemon
$this->httpServer->listen($listener);
}
/**
* Handle incoming request
*
* @param ServerRequestInterface $request
* @return void
*/
private function onRequest(ServerRequestInterface $request)
{
$path = trim($request->getUri()->getPath(), '/');
@@ -98,8 +126,17 @@ class NtfiDaemon
return Response::plaintext("OK");
}
/**
* Try to publish a message based on an incoming topic
*
* @param string $path
* @param string $type
* @param string $body
* @return PromiseInterface
*/
private function doPublish(string $path, string $type, string $body): PromiseInterface
{
printf("in: %s (%s) %d bytes\n", $path, $type, strlen($body));
foreach ($this->channels as $pattern => $channel) {
$re = '/^'.preg_replace('/\{(.+?)\}/', '(?P<$1>[a-zA-Z0-9-_]+)', $pattern).'$/';
// printf("pattern={%s} re={%s}\n", $pattern, $re);
@@ -119,10 +156,23 @@ class NtfiDaemon
});
}
private function publish(string $connection, string $topic, string $type, string $body)
/**
* Publish a message to a defined server, specificed in $connection.
*
* @param string $connection
* @param string $topic
* @param string $type
* @param string $body
* @return PromiseInterface
* @throws \Exception if the configuration is invalid
*/
private function publish(string $connection, string $topic, string $type, string $body): PromiseInterface
{
printf("out: %s %s (%s) %d bytes\n", $connection, $topic, $type, strlen($body));
$d = new Deferred();
$serverInfo = $this->servers[$connection] ?? throw new \Exception("The server '{$connection}' is not configured");
if (isset($serverInfo['token']) && $serverInfo['token']) {
$browser = new Browser();
@@ -130,9 +180,6 @@ class NtfiDaemon
}
$url = sprintf("https://%s/%s", $serverInfo['server'], $topic);
echo $url;
$d->resolve(new Response());
return $d->promise();
$browser->post($url, [
'content-type' => $type,