Post scribbles automatically to Mastodon
All checks were successful
Deploy / deploy (push) Successful in 3s

This commit is contained in:
Marcel Kapfer 2025-02-06 19:25:06 +01:00
parent d3b5609515
commit 1898705e4d
Signed by: mmk2410
GPG key ID: CADE6F0C09F21B09
2 changed files with 63 additions and 2 deletions

View file

@ -1,9 +1,13 @@
<?php
use Kirby\Cms\App as Kirby;
use Kirby\Cms\Page;
use Kirby\Filesystem\F;
use Mmk2410\KirbyHelpers\Controller\ScribbleController;
use Mmk2410\KirbyHelpers\Helpers\Mastodon;
F::loadClasses([
'Mmk2410\\KirbyHelpers\\Helpers\\Mastodon' => 'src/Helpers/Mastodon.php',
'Mmk2410\\KirbyHelpers\\RssFeed' => 'src/RssFeed.php',
'Mmk2410\\KirbyHelpers\\Middleware\\ApiAuthentication' => 'src/Middleware/ApiAuthentication.php',
'Mmk2410\\KirbyHelpers\\Controller\\ScribbleController' => 'src/Controller/ScribbleController.php',
@ -13,8 +17,20 @@ Kirby::plugin('mmk2410/kirby-helpers', [
'routes' => [
[
'pattern' => 'my/api/v1/scribble',
'action' => fn () => (new Mmk2410\KirbyHelpers\Controller\ScribbleController())->addScribble(),
'action' => fn () => (new ScribbleController())->addScribble(),
'method' => 'POST'
],
]
],
'hooks' => [
'page.changeStatus:after' => function (Page $newPage, Page $oldPage): void {
$ignore = ($newPage->template()->name() !== 'scribble')
|| (!$newPage->isListed())
|| ($oldPage->status() === $newPage->status());
if ($ignore) {
return;
}
(new Mastodon())->post($newPage);
}
],
]);

View file

@ -0,0 +1,45 @@
<?php
namespace Mmk2410\KirbyHelpers\Helpers;
use Kirby\Cms\Page;
class Mastodon
{
private const DEFAULT_VISIBILITY = 'public';
public function post(Page $page): void
{
$statusText = $page->content()->get('text');
$this->postStatus($statusText);
}
private function postStatus(
string $status,
string $visibility = self::DEFAULT_VISIBILITY
): void
{
$apiUrl = 'https://'
. kirby()->option('mmk2410.kirby-helpers.mastodon-domain')
. '/api/v1/statuses';
$apiToken = kirby()->option('mmk2410.kirby-helpers.mastodon-token');
$body = json_encode([
'status' => $status,
'visibility'=> $visibility
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiToken",
'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
}
}