webmentions/index.php

74 lines
2.6 KiB
PHP
Raw Permalink Normal View History

<?php declare(strict_types=1);
require_once __DIR__ . "/vendor/autoload.php";
use Lewisdale\Webmentions\Api\WebmentionApi;
use Lewisdale\Webmentions\Endpoint;
use Lewisdale\Webmentions\Exceptions\InvalidSourceException;
use Lewisdale\Webmentions\Exceptions\InvalidTargetException;
use Lewisdale\Webmentions\Exceptions\InvalidUrlException;
use Lewisdale\Webmentions\Exceptions\SourceNotFoundException;
use Lewisdale\Webmentions\Exceptions\TargetNotMentionedException;
use Lewisdale\Webmentions\Gateways\SqliteGateway;
use Lewisdale\Webmentions\Router\Request;
use Lewisdale\Webmentions\Router\Response;
use Lewisdale\Webmentions\Router\Router;
use Lewisdale\Webmentions\Router\StatusCode;
use Lewisdale\Webmentions\Webmention;
use Symfony\Component\HttpClient\HttpClient;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$router = new Router();
$gateway = new SqliteGateway($_ENV["DB"]);
$apiController = new WebmentionApi($gateway);
$router->post("/send", function (Request $req, Response $response) {
2023-03-14 21:08:33 +00:00
$mentioner = new Webmention();
$source = $req->query["source"];
try {
$mentioner->sendForPage($source);
return;
} catch (InvalidSourceException $e) {
$response->status_code = StatusCode::BadRequest;
return $e->getMessage();
}
});
$router->post("/endpoint", function (Request $req, Response $response) use ($gateway) {
$source = $req->post['source'];
$target = $req->post['target'];
$endpoint = new Endpoint(HttpClient::create(), $gateway);
try {
2024-03-12 09:42:48 +00:00
$id = $endpoint->receiveWebmention($source, $target);
$response->header('Location', "/webmention/" . $id);
$response->status_code = StatusCode::Created;
} catch (InvalidUrlException) {
$response->status_code = StatusCode::BadRequest;
return "Source and target must be valid URLs";
} catch (InvalidTargetException) {
$response->status_code = StatusCode::BadRequest;
return "Target must be on the domain lewisdale.dev";
} catch (SourceNotFoundException $e) {
$response->status_code = StatusCode::BadRequest;
return "Source URL was unreachable";
} catch (TargetNotMentionedException) {
$response->status_code = StatusCode::BadRequest;
return "Source does not mention the target";
}
});
2024-03-12 09:42:48 +00:00
$router->get('/webmention/(\d+)', [$apiController, "get"]);
2023-03-14 21:08:33 +00:00
$router->get('/', fn($req, $res) => "<h1>Webmention server</h1>");
$router->get('/api/webmentions', [$apiController, "list"]);
$router->get('/api/webmentions/(\d+)', [$apiController, "get"]);
2023-03-14 21:08:33 +00:00
$router->dispatch();