You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Telegram/AdministratorTelegramChanne...

241 lines
9.3 KiB
PHP

<?php
namespace App\Services\Telegram;
use App\Models\Configurations;
use App\Models\User;
use App\Services\Config;
use App\Services\TicketTelegramConfig;
/**
* Shared low-level administrator Telegram channel.
*
* It owns only authoritative destination resolution and a single remote send.
* Ticket and abuse-alert ledgers, formatting and reply semantics stay outside.
*/
final class AdministratorTelegramChannel
implements AdministratorTelegramDeliveryChannel
{
private const ALLOWED_OPTIONS = [
'reply_to_message_id',
'allow_sending_without_reply',
'disable_web_page_preview',
];
public function __construct(
private readonly AdministratorTelegramTransport $transport = new TelegramBotApiTransport(),
private readonly AdministratorTelegramRateLimiter $rateLimiter = new DatabaseAdministratorTelegramRateGate()
) {}
public function eligibleAdministrator(int $administratorId): bool
{
$allowed = array_map('intval', explode(',', (string) Config::get('super_admin', '')));
if ($administratorId <= 0 || !in_array($administratorId, $allowed, true)) {
return false;
}
$user = User::find($administratorId);
return $user !== null && (bool) $user->is_admin && (int) $user->enable === 1;
}
/**
* Resolve the authoritative private-chat destination. Old binding rows are
* upgraded once with a generation while holding the configuration row lock.
*/
public function currentDestination(): ?AdministratorTelegramDestination
{
try {
$runtime = TicketTelegramConfig::runtimeForDelivery();
} catch (\Throwable $exception) {
throw new AdministratorTelegramLocalUnavailable(
'Administrator Telegram configuration is temporarily unavailable'
);
}
if ($runtime === null) {
return null;
}
return $this->boundDestination();
}
/** Resolve a stored binding even while outbound Telegram is disabled. */
public function boundDestination(): ?AdministratorTelegramDestination
{
$row = Configurations::where('name', TicketTelegramConfig::BINDING)->first();
$state = self::readState($row);
$destination = $this->destinationFromState($state);
if ($destination !== null) {
return $destination;
}
if ($row === null || !$this->eligibleBindingState($state, false)) {
return null;
}
return (new Configurations())->getConnection()->transaction(function (): ?AdministratorTelegramDestination {
$locked = Configurations::where('name', TicketTelegramConfig::BINDING)
->lockForUpdate()->first();
$current = self::readState($locked);
if ($locked === null || !$this->eligibleBindingState($current, false)) {
return null;
}
if (preg_match(
'/^[a-f0-9]{32}$/D',
(string) ($current['binding_generation'] ?? '')
) !== 1) {
$current['binding_generation'] = bin2hex(random_bytes(16));
$locked->value = json_encode($current, JSON_THROW_ON_ERROR);
if (!$locked->save()) {
throw new \RuntimeException('Telegram binding generation storage failed');
}
}
return $this->destinationFromState($current);
});
}
/**
* Send once to the expected binding generation. A concurrent unbind/rebind
* is rejected before the remote request, so a reserved business delivery
* can never drift to another administrator or chat.
*
* @param array<string, int|string|bool> $options
*/
public function send(
AdministratorTelegramDestination $expected,
string $text,
array $options = []
): int {
$textLength = mb_strlen($text, 'UTF-8');
if ($textLength < 1 || $textLength > 4096) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::PAYLOAD_INVALID,
'Telegram message length is invalid'
);
}
foreach (array_keys($options) as $key) {
if (!is_string($key) || !in_array($key, self::ALLOWED_OPTIONS, true)) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::PAYLOAD_INVALID,
'Telegram send option is not allowed'
);
}
}
if (isset($options['reply_to_message_id'])
&& (!is_int($options['reply_to_message_id'])
|| $options['reply_to_message_id'] <= 0)) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::PAYLOAD_INVALID,
'Telegram reply message id is invalid'
);
}
// Both reads are authoritative. Config runtime also rejects disabled or
// unreadable credentials; the binding read fences recipient changes.
try {
$config = TicketTelegramConfig::runtimeForDelivery();
} catch (\Throwable $exception) {
throw new AdministratorTelegramLocalUnavailable(
'Administrator Telegram configuration is temporarily unavailable'
);
}
if ($config === null) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::CHANNEL_UNAVAILABLE,
'Administrator Telegram configuration is unavailable'
);
}
try {
$current = $this->boundDestination();
} catch (\Throwable $exception) {
throw new AdministratorTelegramLocalUnavailable(
'Administrator Telegram binding is temporarily unavailable'
);
}
if ($current === null || !$current->equals($expected)) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::DESTINATION_CHANGED,
'Administrator Telegram destination changed'
);
}
// This local transaction finishes before the remote boundary. A gate
// failure is therefore known not to have contacted Telegram.
$this->rateLimiter->acquire($current);
// A queued permit may wait for the preceding sender. Re-read both the
// credential and recipient after that wait so an unbind, rebind or
// disable can never send with the stale pre-gate snapshot.
try {
$config = TicketTelegramConfig::runtimeForDelivery();
} catch (\Throwable $exception) {
throw new AdministratorTelegramLocalUnavailable(
'Administrator Telegram configuration is temporarily unavailable'
);
}
if ($config === null) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::CHANNEL_UNAVAILABLE,
'Administrator Telegram configuration is unavailable'
);
}
try {
$current = $this->boundDestination();
} catch (\Throwable $exception) {
throw new AdministratorTelegramLocalUnavailable(
'Administrator Telegram binding is temporarily unavailable'
);
}
if ($current === null || !$current->equals($expected)) {
throw new AdministratorTelegramPreflightException(
AdministratorTelegramPreflightException::DESTINATION_CHANGED,
'Administrator Telegram destination changed'
);
}
try {
return $this->transport->sendMessage(
(string) $config['bot_token'],
$current->chatId,
$text,
$options
);
} catch (AdministratorTelegramRemoteEffectUnknown $exception) {
throw $exception;
} catch (\Throwable $exception) {
throw new AdministratorTelegramRemoteEffectUnknown(
'Administrator Telegram remote effect is unknown'
);
}
}
private function destinationFromState(array $state): ?AdministratorTelegramDestination
{
if (!$this->eligibleBindingState($state, true)) {
return null;
}
return new AdministratorTelegramDestination(
(int) $state['bound_admin_id'],
(string) $state['chat_id'],
(string) $state['binding_generation']
);
}
private function eligibleBindingState(array $state, bool $requireGeneration): bool
{
$administratorId = (int) ($state['bound_admin_id'] ?? 0);
$chatId = $state['chat_id'] ?? null;
if ((!is_string($chatId) && !is_int($chatId))
|| preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1
|| !$this->eligibleAdministrator($administratorId)) {
return false;
}
return !$requireGeneration || preg_match(
'/^[a-f0-9]{32}$/D',
(string) ($state['binding_generation'] ?? '')
) === 1;
}
private static function readState($row): array
{
$state = $row === null ? [] : json_decode((string) $row->value, true);
return is_array($state) ? $state : [];
}
}