start using objects

This commit is contained in:
Christopher Teutsch 2023-01-26 13:52:00 +01:00
parent 2145491138
commit 759d05d47c
4 changed files with 103 additions and 56 deletions

20
app/State.php Normal file
View File

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace DorfJetzt;
class State
{
public string $description;
public string $svg_name;
public string $color;
public function __construct(string $description, string $svg_name, string $color)
{
$this->description = $description;
$this->svg_name = $svg_name;
$this->color = $color;
}
}

View File

@ -1,4 +1,9 @@
{ {
"autoload": {
"psr-4": {
"DorfJetzt\\": "app/"
}
},
"require": { "require": {
"johngrogg/ics-parser": "^3", "johngrogg/ics-parser": "^3",
"symfony/http-client": "^6.2", "symfony/http-client": "^6.2",

133
index.php
View File

@ -9,12 +9,17 @@ use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Component\HttpKernel\HttpCache\Store;
use Twig\TwigFilter; use Twig\TwigFilter;
use Twig\NodeVisitor\OptimizerNodeVisitor; use Twig\NodeVisitor\OptimizerNodeVisitor;
use DorfJetzt\State;
#region Configuration
const VISITORS_FILE = '/opt/dorf.jetzt_visitors'; const VISITORS_FILE = '/opt/dorf.jetzt_visitors';
const ICAL_URL = 'https://chaosdorf.de/~derf/cccd_all.ics'; const ICAL_URL = 'https://chaosdorf.de/~derf/cccd_all.ics';
const HTTP_CACHE = '/tmp/dorf.jetzt/http_cache'; const HTTP_CACHE = '/tmp/dorf.jetzt/http_cache';
const TMPL_CACHE = '/tmp/dorf.jetzt/twig_cache'; const TMPL_CACHE = '/tmp/dorf.jetzt/twig_cache';
const ROOM_STATE_URL = 'https://chaosdorf.de/raumstatus/status.png'; const ROOM_STATE_URL = 'https://chaosdorf.de/raumstatus/status.png';
const DEFAULT_TZ = 'Europe/Berlin';
#endregion
const INVALID_UAS = [ const INVALID_UAS = [
"AhrefsBot", "AhrefsBot",
@ -38,41 +43,44 @@ const HASH_TO_STATE = [
'0' => 'error', '0' => 'error',
]; ];
$STATE_MAP = [ function stateMap(string $state): State
'closed' => (object) [ {
'state_string' => 'Das Dorf ist gerade <em>geschlossen</em>.', return match ($state) {
'svg' => 'lock', 'closed' => new State(
'color' => 'red', 'Das Dorf ist gerade <em>geschlossen</em>.',
], 'lock',
'maybe_open' => (object) [ 'red',
'state_string' => 'Das Dorf ist gerade <em>vielleicht geöffnet</em>: </p><p>Der Clubraum ist offen, aber es findet keine Veranstaltung statt.</p><p> ),
'maybe_open' => new State(
'Das Dorf ist gerade <em>vielleicht geöffnet</em>: </p><p>Der Clubraum ist offen, aber es findet keine Veranstaltung statt.</p><p>
Der Status kann sich also kurzfristig ändern.', Der Status kann sich also kurzfristig ändern.',
'svg' => 'done', 'done',
'color' => 'brown', 'brown',
], ),
'open' => (object) [ 'open' => new State(
'state_string' => 'Das Dorf ist gerade <em>geöffnet</em>.</p><p> 'Das Dorf ist gerade <em>geöffnet</em>.</p><p>
Komm gerne vorbei.', Komm gerne vorbei.',
'svg' => 'done', 'done',
'color' => 'green', 'green',
], ),
'private' => (object) [ 'private' => new State(
'state_string' => 'Das Dorf ist gerade <em>privat</em>: </p><p>Es sind Leute da, aber der Clubraum ist nicht geöffnet.</p><p> 'Das Dorf ist gerade <em>privat</em>: </p><p>Es sind Leute da, aber der Clubraum ist nicht geöffnet.</p><p>
Komm gerne vorbei (aber frag lieber vorher, wie lange noch Leute da sind).', Komm gerne vorbei (aber frag lieber vorher, wie lange noch Leute da sind).',
'svg' => 'lock', 'lock',
'color' => 'fdd835', 'fdd835',
], ),
'unknown' => (object) [ 'unknown' => new State(
'state_string' => 'Der Status vom Dorf ist gerade <em>unbekannt</em>', 'Der Status vom Dorf ist gerade <em>unbekannt</em>',
'svg' => 'warning', 'warning',
'color' => 'orange', 'orange',
], ),
'error' => (object) [ 'error' => new State(
'state_string' => 'Der Server konnte den Status vom Dorf nicht abrufen.', 'Der Server konnte den Status vom Dorf nicht abrufen.',
'svg' => 'error', 'error',
'color' => 'blue', 'blue',
], ),
]; };
}
function hasValidUa(): bool function hasValidUa(): bool
{ {
@ -85,22 +93,25 @@ function hasValidUa(): bool
return false; return false;
} }
function dateTimeFromEvent(ICal $ical, object $event): DateTimeImmutable { function dateTimeFromEvent(ICal $ical, object $event): DateTimeImmutable
{
return DateTimeImmutable::createFromMutable($ical->iCalDateToDateTime($event->dtstart_array[3])); return DateTimeImmutable::createFromMutable($ical->iCalDateToDateTime($event->dtstart_array[3]));
} }
/** /**
* @return array<int, array<string, DateTime|string|bool>> * @return array{summary: string, url: string, start: DateTimeImmutable, end: DateTimeImmutable}[]
*/ */
function prepare_events(ICal $ical, array $events): array function prepareEvents(ICal $ical, array $events): array
{ {
$returns = []; $returns = [];
foreach ($events as $event) { foreach ($events as $event) {
$start = dateTimeFromEvent($ical, $event); $start = dateTimeFromEvent($ical, $event);
$end = $start->add(new DateInterval($event->duration)); $end = $start->add(new DateInterval($event->duration));
$url = strval($event->url);
$summary = strval($event->summary);
$returns[] = [ $returns[] = [
'summary' => $event->summary, 'summary' => $summary,
'url' => $event->url, 'url' => $url,
'start' => $start, 'start' => $start,
'end' => $end, 'end' => $end,
]; ];
@ -108,26 +119,37 @@ function prepare_events(ICal $ical, array $events): array
return $returns; return $returns;
} }
function getState(\Symfony\Contracts\HttpClient\HttpClientInterface $http): State
{
try {
$response = $http->request('GET', ROOM_STATE_URL);
$hash = md5($response->getContent());
if (!array_key_exists($hash, HASH_TO_STATE)){
error_log("Encountered unknown state hash $hash");
}
return stateMap(HASH_TO_STATE[$hash]);
} catch (\Exception $e) {
return stateMap('error');
}
}
$store = new Store(HTTP_CACHE); $store = new Store(HTTP_CACHE);
$client = HttpClient::create(); $client = HttpClient::create();
$client = new CachingHttpClient($client, $store, ['default_ttl' => 60, 'allow_revalidate' => true]); $client = new CachingHttpClient($client, $store, ['default_ttl' => 60, 'allow_revalidate' => true]);
$state = 'error'; $state_obj = getState($client);
try {
$response = $client->request('GET', ROOM_STATE_URL);
$hash = md5($response->getContent());
} catch (\Exception $e) { $ical = new ICal(options: [
$hash = 0;
}
$state = HASH_TO_STATE[$hash];
$ical = new ICal(false, [
'defaultSpan' => 2, 'defaultSpan' => 2,
'defaultTimeZone' => 'Europe/Berlin', 'defaultTimeZone' => DEFAULT_TZ,
'defaultWeekStart' => 'MO', 'defaultWeekStart' => 'MO',
'filterDaysBefore' => '1', 'filterDaysBefore' => '1',
]); ]);
$ical->initUrl(ICAL_URL, $acceptLanguage = 'de'); $ical->initUrl(ICAL_URL, userAgent: 'dorf.jetzt', acceptLanguage: 'de');
$events = $ical->eventsFromInterval('2 week'); $events = $ical->eventsFromInterval('2 week') or [];
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']); $locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
setlocale(LC_TIME, $locale); setlocale(LC_TIME, $locale);
@ -138,7 +160,8 @@ if (is_string($visitors)) {
} else { } else {
$visitors = 0; $visitors = 0;
} }
$state_obj = $STATE_MAP[$state];
$loader = new \Twig\Loader\FilesystemLoader('templates'); $loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [ $twig = new \Twig\Environment($loader, [
@ -162,15 +185,13 @@ function formatEndDt(?DateTimeImmutable $end, ?DateTimeImmutable $start, string
} }
$twig->addFilter(new TwigFilter('end_datetime', 'formatEndDt')); $twig->addFilter(new TwigFilter('end_datetime', 'formatEndDt'));
//$twig->addExtension(new \Twig\Extra\Intl\IntlExtension()); $twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone(DEFAULT_TZ);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Europe/Berlin');
$render_evts = prepare_events($ical, $events);
echo ($twig->render("Main.twig", [ echo ($twig->render("Main.twig", [
'visitors' => $visitors, 'visitors' => $visitors,
'state_svg' => $state_obj->svg, 'state_svg' => $state_obj->svg_name,
'state_color' => $state_obj->color, 'state_color' => $state_obj->color,
'state_string' => $state_obj->state_string, 'state_string' => $state_obj->description,
'events' => $render_evts, 'events' => prepareEvents($ical, $events),
])); ]));
/* Initialising values */ /* Initialising values */
if (hasValidUa()) { if (hasValidUa()) {

View File

@ -8,6 +8,7 @@
> >
<projectFiles> <projectFiles>
<file name="index.php" /> <file name="index.php" />
<directory name="app" />
<ignoreFiles> <ignoreFiles>
<directory name="vendor" /> <directory name="vendor" />
</ignoreFiles> </ignoreFiles>