42 lines
2.0 KiB
PHP
42 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Channels\ICal;
|
|
|
|
use App\Models\Channel;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ICalExport
|
|
{
|
|
public function __construct(private ICalFeed $feed, private ICalParser $parser) {}
|
|
|
|
public function build(Channel $channel, string $method = 'GET', ?string $userAgent = null): ?string
|
|
{
|
|
$requestedAt = now();
|
|
|
|
return DB::transaction(function () use ($channel, $method, $userAgent, $requestedAt): ?string {
|
|
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
|
if ($locked->exportsOccupations()) {
|
|
$body = $this->feed->build($locked);
|
|
$this->parser->parse($body);
|
|
$locked->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
|
|
}
|
|
$lastRequest = $locked->last_export_requested_at;
|
|
$locked->forceFill(['last_export_requested_at' => $lastRequest?->greaterThan($requestedAt) ? $lastRequest : $requestedAt])->saveQuietly();
|
|
$userAgent = str_replace(array_filter([$locked->export_token, $locked->previous_export_token]), '[Token entfernt]', $userAgent ?? '');
|
|
$locked->exportRequests()->create([
|
|
'requested_at' => $requestedAt,
|
|
'method' => $method,
|
|
'user_agent' => filled($userAgent) ? mb_substr(str_replace(["\r", "\n"], ' ', $userAgent), 0, 512) : null,
|
|
'response_status' => $locked->export_snapshot === null ? 503 : 200,
|
|
'export_state' => $locked->export_snapshot === null ? 'unavailable' : ($locked->exportsOccupations() ? 'live' : 'frozen'),
|
|
]);
|
|
$expired = $locked->exportRequests()->skip(max(1, (int) config('channels.export_request_history_limit', 100)))->take(1000)->pluck('id');
|
|
if ($expired->isNotEmpty()) {
|
|
$locked->exportRequests()->whereIn('id', $expired)->delete();
|
|
}
|
|
|
|
return $locked->export_snapshot;
|
|
});
|
|
}
|
|
}
|