From 1898705e4d28f579f70579823f34d87bb133f214 Mon Sep 17 00:00:00 2001 From: Marcel Kapfer Date: Thu, 6 Feb 2025 19:25:06 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Post=20scribbles=20automatically=20?= =?UTF-8?q?to=20Mastodon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- site/plugins/kirby-helpers/index.php | 20 ++++++++- .../kirby-helpers/src/Helpers/Mastodon.php | 45 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 site/plugins/kirby-helpers/src/Helpers/Mastodon.php diff --git a/site/plugins/kirby-helpers/index.php b/site/plugins/kirby-helpers/index.php index a82813b..754d625 100644 --- a/site/plugins/kirby-helpers/index.php +++ b/site/plugins/kirby-helpers/index.php @@ -1,9 +1,13 @@ '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); + } + ], ]); diff --git a/site/plugins/kirby-helpers/src/Helpers/Mastodon.php b/site/plugins/kirby-helpers/src/Helpers/Mastodon.php new file mode 100644 index 0000000..e4edcca --- /dev/null +++ b/site/plugins/kirby-helpers/src/Helpers/Mastodon.php @@ -0,0 +1,45 @@ +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); + } +}