feat: action links, telegram webhook and channels API

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw
This commit is contained in:
nikita.hohlov
2026-09-04 07:52:12 -03:00
parent 6138ac7bb0
commit 90d17ec378
8 changed files with 450 additions and 10 deletions

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers;
use App\Delivery\EventActions;
use App\Models\Delivery;
use App\Models\Event;
use Illuminate\Http\JsonResponse;
/** Кнопки из каналов: подписанные ссылки по action_token доставки. Без SSO и CSRF. */
class ActionController extends Controller
{
public function __construct(private readonly EventActions $actions) {}
public function ack(string $token): JsonResponse
{
$event = $this->eventFor($token);
$this->actions->ack($event);
return response()->json(['state' => $event->fresh()->state->value]);
}
public function done(string $token): JsonResponse
{
$event = $this->eventFor($token);
$this->actions->done($event);
return response()->json(['state' => $event->fresh()->state->value]);
}
private function eventFor(string $token): Event
{
$delivery = Delivery::where('action_token', $token)->with('event.user')->first();
abort_if($delivery === null, 404, 'Неизвестный токен');
abort_if($delivery->event->isTerminal(), 410, 'Событие уже закрыто');
return $delivery->event;
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Http\Controllers\Me;
use App\Enums\ChannelType;
use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class ChannelsController extends Controller
{
public function index(Request $request): JsonResponse
{
/** @var User $user */
$user = $request->attributes->get('user');
return response()->json(['channels' => $user->channels()->orderBy('id')->get()->map(self::present(...))->values()]);
}
public function store(Request $request): JsonResponse
{
/** @var User $user */
$user = $request->attributes->get('user');
$data = $request->validate([
'type' => ['required', 'in:webhook'],
'config' => ['required', 'array'],
'config.deliver_url' => ['required', 'url'],
'config.presence_url' => ['required', 'url'],
], ['type.in' => 'Через API добавляется только webhook; Telegram подключается через /start.']);
$channel = $user->channels()->create([
'type' => ChannelType::Webhook,
'config' => ['deliver_url' => $data['config']['deliver_url'], 'presence_url' => $data['config']['presence_url']],
'enabled' => true,
]);
return response()->json(self::present($channel), 201);
}
public function destroy(Request $request, int $channel): Response
{
/** @var User $user */
$user = $request->attributes->get('user');
$model = $user->channels()->whereKey($channel)->firstOrFail();
if ($model->type === ChannelType::Web) {
throw ValidationException::withMessages(['channel' => 'Веб-канал удалить нельзя']);
}
$model->delete();
return response()->noContent();
}
public function telegramLink(Request $request): JsonResponse
{
/** @var User $user */
$user = $request->attributes->get('user');
$code = Str::upper(Str::random(6));
Cache::put("tg:link:{$code}", $user->id, 900);
return response()->json([
'code' => $code,
'bot_url' => 'https://t.me/'.config('hado.telegram.username').'?start='.$code,
]);
}
/** @return array<string,mixed> */
public static function present(Channel $channel): array
{
return [
'id' => $channel->id,
'type' => $channel->type->value,
'config' => $channel->config,
'enabled' => $channel->enabled,
];
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use App\Channels\TelegramChannel;
use App\Delivery\EventActions;
use App\Enums\ChannelType;
use App\Models\Channel;
use App\Models\Delivery;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
class TelegramWebhookController extends Controller
{
public function __construct(
private readonly TelegramChannel $telegram,
private readonly EventActions $actions,
) {}
public function __invoke(Request $request): Response
{
$expected = (string) config('hado.telegram.webhook_secret');
$given = (string) $request->header('X-Telegram-Bot-Api-Secret-Token', '');
abort_unless($expected !== '' && hash_equals($expected, $given), 403);
if (is_array($message = $request->input('message'))) {
$this->message($message);
}
if (is_array($callback = $request->input('callback_query'))) {
$this->callback($callback);
}
return response()->noContent();
}
private function message(array $message): void
{
$chatId = $message['chat']['id'] ?? null;
if ($chatId === null) {
return;
}
$this->telegram->touch($chatId);
if (! preg_match('~^/start\s+(\S+)~', (string) ($message['text'] ?? ''), $m)) {
return;
}
$userId = Cache::pull('tg:link:'.$m[1]);
if ($userId === null) {
$this->telegram->sendText($chatId, 'Код не найден или устарел. Сгенерируй новый в инбоксе Hado.');
return;
}
Channel::updateOrCreate(
['user_id' => $userId, 'type' => ChannelType::Telegram->value],
['config' => ['chat_id' => $chatId], 'enabled' => true],
);
$this->telegram->sendText($chatId, 'Подключено');
}
private function callback(array $callback): void
{
$chatId = $callback['message']['chat']['id'] ?? null;
if ($chatId !== null) {
$this->telegram->touch($chatId);
}
[$action, $token] = array_pad(explode(':', (string) ($callback['data'] ?? ''), 2), 2, '');
$delivery = Delivery::where('action_token', $token)->with('event.user')->first();
if ($delivery === null || $delivery->event->isTerminal() || ! in_array($action, ['ack', 'done'], true)) {
$this->telegram->answerCallback((string) $callback['id'], 'Уже неактуально');
return;
}
if ($action === 'done') {
$this->actions->done($delivery->event);
$this->telegram->answerCallback((string) $callback['id'], 'Закрыто');
} else {
$this->actions->ack($delivery->event);
$this->telegram->answerCallback((string) $callback['id'], 'Ок, напомню позже');
}
}
}