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/TicketTelegramNotifier.php

674 lines
26 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services;
use App\Models\CloudInstance;
use App\Models\Configurations;
use App\Models\TicketTelegramDelivery;
use App\Models\User;
use App\Services\Ticket\ReplyTicketCommand;
use App\Services\Ticket\TicketEvent;
use App\Services\Ticket\TicketIdempotencyConflict;
use App\Services\Ticket\TicketNotificationDispatcher;
use App\Services\Ticket\TicketReplyStateConflict;
use App\Services\Ticket\TicketTelegramNotificationResult;
use App\Services\Ticket\TicketThreadService;
use TelegramBot\Api\BotApi;
/** Administrator-only ticket alerts and replies to mapped notification messages. */
final class TicketTelegramNotifier
{
private const KEY = TicketTelegramConfig::BINDING;
public const BINDING_TTL = 300;
public static function enabled(): bool
{
try {
return (bool) TicketTelegramConfig::publicValues()['enabled'];
} catch (\Throwable $exception) {
return false;
}
}
public static function configured(): bool
{
try {
return (bool) TicketTelegramConfig::publicValues()['configured'];
} catch (\Throwable $exception) {
return false;
}
}
public static function authorizeWebhook(string $header): bool
{
try {
$config = TicketTelegramConfig::runtime(true);
return hash_equals($config['webhook_secret'], $header);
} catch (\Throwable $exception) {
return false;
}
}
public static function bindingStatus(): array
{
$state = self::readState(Configurations::where('name', self::KEY)->first());
$adminId = (int) ($state['bound_admin_id'] ?? 0);
return ['bound' => !empty($state['chat_id']) && self::eligibleAdmin($adminId), 'admin_id' => $adminId];
}
public static function createBinding(int $adminId): array
{
TicketTelegramConfig::runtime(true);
if (!self::eligibleAdmin($adminId)) {
throw new \RuntimeException('只有超级管理员可以绑定工单通知');
}
$code = bin2hex(random_bytes(24));
self::ensureBindingRow();
(new Configurations())->getConnection()->transaction(function () use ($adminId, $code) {
$row = Configurations::where('name', self::KEY)->lockForUpdate()->firstOrFail();
$state = self::readState($row);
$state['pending_hash'] = hash('sha256', $code);
$state['pending_admin_id'] = $adminId;
$state['pending_expires_at'] = time() + self::BINDING_TTL;
$row->value = json_encode($state, JSON_THROW_ON_ERROR);
if (!$row->save()) {
throw new \RuntimeException('Administrator Telegram binding storage failed');
}
});
return ['code' => $code, 'expires_in' => self::BINDING_TTL];
}
public static function unbind(): void
{
Configurations::where('name', self::KEY)->delete();
}
/** Create the binding state without relying on mass-assignable model attributes. */
private static function ensureBindingRow(): void
{
if (Configurations::where('name', self::KEY)->first() !== null) {
return;
}
$row = new Configurations();
$row->name = self::KEY;
$row->value = '{}';
try {
$row->save();
} catch (\Throwable $exception) {
// Another request may have created the uniquely named binding row.
if (Configurations::where('name', self::KEY)->first() === null) {
throw $exception;
}
}
}
public static function bindingCommand(array $update): ?array
{
$message = $update['message'] ?? null;
if (!is_array($message) || ($message['chat']['type'] ?? '') !== 'private'
|| !empty($message['from']['is_bot']) || !empty($message['forward_origin'])
|| !empty($message['forward_from']) || !empty($message['forward_date'])) {
return null;
}
$chatId = (string) ($message['chat']['id'] ?? '');
$senderId = (string) ($message['from']['id'] ?? '');
if (!preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) || $chatId !== $senderId
|| !preg_match('/^\/start\s+([a-f0-9]{48})$/D', (string) ($message['text'] ?? ''), $matches)) {
return null;
}
return ['chat_id' => $chatId, 'code' => $matches[1]];
}
public static function handleUpdate(array $update): bool
{
$command = self::bindingCommand($update);
if ($command === null) {
return self::handleTicketReply($update);
}
$bound = (new Configurations())->getConnection()->transaction(function () use ($command) {
$row = Configurations::where('name', self::KEY)->lockForUpdate()->first();
$state = self::readState($row);
$adminId = (int) ($state['pending_admin_id'] ?? 0);
if ($row === null || (int) ($state['pending_expires_at'] ?? 0) <= time()
|| !hash_equals((string) ($state['pending_hash'] ?? ''), hash('sha256', $command['code']))
|| !self::eligibleAdmin($adminId)) {
return false;
}
// One-time token consumed atomically; replay cannot change the recipient.
$row->value = json_encode([
'bound_admin_id' => $adminId,
'chat_id' => $command['chat_id'],
'binding_generation' => bin2hex(random_bytes(16)),
], JSON_THROW_ON_ERROR);
if (!$row->save()) {
throw new \RuntimeException('Administrator Telegram binding storage failed');
}
return true;
});
if (!$bound) {
return false;
}
// The binding is already committed before the remote acknowledgement.
// A transient Telegram failure must not revive the one-time code or
// cause Telegram to replay a successful binding transaction.
self::sendBindingConfirmation($command['chat_id']);
return true;
}
private static function handleTicketReply(array $update): bool
{
$command = self::ticketReplyCommand($update);
if ($command === null) {
return false;
}
$state = self::deliveryBindingState();
$adminId = (int) ($state['bound_admin_id'] ?? 0);
if (($state['chat_id'] ?? null) !== $command['chat_id']
|| preg_match('/^[a-f0-9]{32}$/D',
(string) ($state['binding_generation'] ?? '')) !== 1
|| !self::eligibleAdmin($adminId)) {
return false;
}
$delivery = TicketTelegramDelivery::where(
'binding_generation', (string) $state['binding_generation']
)->where('chat_id', $command['chat_id'])
->where('telegram_message_id', $command['reply_to_message_id'])
->where('state', 'sent')->first();
if ($delivery === null || (int) $delivery->bound_admin_id !== $adminId) {
self::sendReplyAcknowledgement(
$command['chat_id'],
$command['message_id'],
'无法识别这条工单通知,请在管理后台处理。'
);
return true;
}
try {
$result = (new TicketThreadService())->reply(new ReplyTicketCommand(
(int) $delivery->ticket_id,
$adminId,
$command['text'],
1,
null,
null,
true,
'telegram.' . $state['binding_generation']
. '.update.' . $command['update_id'],
1
));
} catch (TicketReplyStateConflict $exception) {
self::sendReplyAcknowledgement(
$command['chat_id'], $command['message_id'], $exception->getMessage()
);
return true;
} catch (TicketIdempotencyConflict $exception) {
self::sendReplyAcknowledgement(
$command['chat_id'],
$command['message_id'],
'这条 Telegram 更新已用于其他回复,请在管理后台核对。'
);
return true;
} catch (\InvalidArgumentException $exception) {
self::sendReplyAcknowledgement(
$command['chat_id'], $command['message_id'], $exception->getMessage()
);
return true;
}
if ($result === null) {
self::sendReplyAcknowledgement(
$command['chat_id'],
$command['message_id'],
'工单已不存在,请在管理后台核对。'
);
return true;
}
if (!$result->wasCreated) {
return true;
}
(new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result));
self::sendReplyAcknowledgement(
$command['chat_id'],
$command['message_id'],
'✅ 已回复工单 #' . (int) $result->root->id
. "\n用户已可在工单页面查看。"
);
return true;
}
private static function ticketReplyCommand(array $update): ?array
{
$message = $update['message'] ?? null;
$updateId = self::positiveIntegerString($update['update_id'] ?? null);
if (!is_array($message)
|| $updateId === null
|| ($message['chat']['type'] ?? '') !== 'private'
|| !empty($message['from']['is_bot'])
|| !empty($message['via_bot'])
|| !empty($message['sender_chat'])
|| !empty($message['forward_origin'])
|| !empty($message['forward_from'])
|| !empty($message['forward_date'])) {
return null;
}
$chatId = (string) ($message['chat']['id'] ?? '');
$senderId = (string) ($message['from']['id'] ?? '');
$messageId = self::positiveIntegerString($message['message_id'] ?? null);
$replyMessageId = self::positiveIntegerString(
$message['reply_to_message']['message_id'] ?? null
);
$text = $message['text'] ?? null;
if (preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) !== 1
|| $chatId !== $senderId
|| $messageId === null
|| $replyMessageId === null
|| !is_string($text)
|| trim($text) === ''
|| str_starts_with(trim($text), '/')) {
return null;
}
foreach (['animation', 'audio', 'document', 'photo', 'sticker', 'video',
'video_note', 'voice'] as $media) {
if (array_key_exists($media, $message)) {
return null;
}
}
return [
'update_id' => $updateId,
'chat_id' => $chatId,
'message_id' => (int) $messageId,
'reply_to_message_id' => (int) $replyMessageId,
'text' => trim($text),
];
}
private static function positiveIntegerString(mixed $value): ?string
{
if ((!is_int($value) && !is_string($value))
|| preg_match('/^[1-9][0-9]{0,18}$/D', (string) $value) !== 1) {
return null;
}
$value = (string) $value;
$maximum = (string) PHP_INT_MAX;
if (strlen($value) > strlen($maximum)
|| (strlen($value) === strlen($maximum) && strcmp($value, $maximum) > 0)) {
return null;
}
return $value;
}
private static function sendReplyAcknowledgement(
string $chatId,
int $replyToMessageId,
string $text
): void {
try {
$config = TicketTelegramConfig::runtime(true);
(new BotApi($config['bot_token']))->call('sendMessage', [
'chat_id' => $chatId,
'text' => $text,
'reply_to_message_id' => $replyToMessageId,
'allow_sending_without_reply' => 'true',
'disable_web_page_preview' => 'true',
], 10);
} catch (\Throwable $exception) {
// The ticket transaction has already committed. Never request a
// Telegram replay merely because this best-effort receipt failed.
error_log('Administrator Telegram ticket reply confirmation failed');
}
}
public static function notify(TicketEvent $event): TicketTelegramNotificationResult
{
$ticketId = (int) $event->result->root->id;
try {
$public = TicketTelegramConfig::publicValues();
if (!$public['enabled'] || !$public['configured']) {
return TicketTelegramNotificationResult::Skipped;
}
} catch (\Throwable $exception) {
error_log('Administrator ticket Telegram configuration check failed');
return TicketTelegramNotificationResult::Failed;
}
try {
$config = TicketTelegramConfig::runtime(true);
$state = self::deliveryBindingState();
$chatId = $state['chat_id'] ?? null;
if ((!is_string($chatId) && !is_int($chatId))
|| preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1
|| !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) {
return TicketTelegramNotificationResult::Skipped;
}
$text = self::notificationText($event);
[$delivery, $ownsDispatch] = self::reserveDelivery($event, $state, $text);
if (!$ownsDispatch) {
return (string) $delivery->state === 'sent'
? TicketTelegramNotificationResult::Sent
: TicketTelegramNotificationResult::Failed;
}
try {
$result = (new BotApi($config['bot_token']))->call('sendMessage', [
'chat_id' => (string) $chatId,
'text' => $text,
'disable_web_page_preview' => 'true',
], 10);
$messageId = self::telegramMessageId($result);
$updated = TicketTelegramDelivery::where('id', (int) $delivery->id)
->where('state', 'dispatching')->update([
'telegram_message_id' => $messageId,
'state' => 'sent',
'sent_at' => time(),
'updated_at' => time(),
]);
if ((int) $updated !== 1) {
throw new \RuntimeException('Telegram delivery finalization failed');
}
return TicketTelegramNotificationResult::Sent;
} catch (\Throwable $exception) {
self::markDeliveryUnknown((int) $delivery->id);
throw $exception;
}
} catch (\Throwable $exception) {
// SDK error URLs may contain bot secrets. Never log their messages.
error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId);
return TicketTelegramNotificationResult::Failed;
}
}
/**
* @return array{TicketTelegramDelivery, bool}
*/
private static function reserveDelivery(TicketEvent $event, array $state, string $text): array
{
$generation = (string) $state['binding_generation'];
$messageId = (int) $event->result->message->id;
$kind = (string) $event->kind;
$existing = self::deliveryForEvent($generation, $messageId, $kind);
if ($existing !== null) {
self::settleStaleDispatching($existing);
return [$existing, false];
}
$delivery = new TicketTelegramDelivery();
$delivery->binding_generation = $generation;
$delivery->bound_admin_id = (int) $state['bound_admin_id'];
$delivery->chat_id = (string) $state['chat_id'];
$delivery->ticket_id = (int) $event->result->root->id;
$delivery->ticket_message_id = $messageId;
$delivery->event_kind = $kind;
$delivery->telegram_message_id = null;
$delivery->state = 'dispatching';
$delivery->content_hash = hash('sha256', $text);
$delivery->created_at = time();
$delivery->sent_at = null;
$delivery->updated_at = time();
try {
if (!$delivery->save()) {
throw new \RuntimeException('Telegram delivery reservation failed');
}
return [$delivery, true];
} catch (\Throwable $exception) {
// The unique event key elects one sender when dispatchers race.
$existing = self::deliveryForEvent($generation, $messageId, $kind);
if ($existing !== null) {
return [$existing, false];
}
throw $exception;
}
}
private static function settleStaleDispatching(TicketTelegramDelivery $delivery): void
{
if ((string) $delivery->state !== 'dispatching'
|| (int) $delivery->updated_at > time() - 30) {
return;
}
$updated = TicketTelegramDelivery::where('id', (int) $delivery->id)
->where('state', 'dispatching')->update([
'telegram_message_id' => null,
'state' => 'unknown',
'updated_at' => time(),
]);
if ((int) $updated === 1) {
$delivery->telegram_message_id = null;
$delivery->state = 'unknown';
$delivery->updated_at = time();
}
}
private static function deliveryForEvent(
string $generation,
int $messageId,
string $kind
): ?TicketTelegramDelivery {
return TicketTelegramDelivery::where('binding_generation', $generation)
->where('ticket_message_id', $messageId)
->where('event_kind', $kind)->first();
}
private static function telegramMessageId(mixed $result): int
{
$messageId = is_array($result) ? ($result['message_id'] ?? null) : null;
if (is_object($result)) {
if (method_exists($result, 'getMessageId')) {
$messageId = $result->getMessageId();
} elseif (isset($result->message_id)) {
$messageId = $result->message_id;
}
}
if ((!is_int($messageId) && !is_string($messageId))
|| preg_match('/^[1-9][0-9]{0,18}$/D', (string) $messageId) !== 1) {
throw new \RuntimeException('Telegram did not return a valid message identifier');
}
return (int) $messageId;
}
private static function markDeliveryUnknown(int $deliveryId): void
{
try {
TicketTelegramDelivery::where('id', $deliveryId)
->where('state', 'dispatching')->update([
'telegram_message_id' => null,
'state' => 'unknown',
'updated_at' => time(),
]);
} catch (\Throwable $exception) {
error_log('Administrator ticket Telegram delivery reconciliation failed');
}
}
private static function deliveryBindingState(): array
{
$row = Configurations::where('name', self::KEY)->first();
$state = self::readState($row);
if (preg_match('/^[a-f0-9]{32}$/D', (string) ($state['binding_generation'] ?? '')) === 1) {
return $state;
}
if ($row === null || empty($state['chat_id'])
|| !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) {
return $state;
}
return (new Configurations())->getConnection()->transaction(function () {
$locked = Configurations::where('name', self::KEY)->lockForUpdate()->first();
$current = self::readState($locked);
if ($locked === null || empty($current['chat_id'])
|| !self::eligibleAdmin((int) ($current['bound_admin_id'] ?? 0))) {
return $current;
}
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 $current;
});
}
private static function notificationText(TicketEvent $event): string
{
$root = $event->result->root;
$message = $event->result->message;
$ticketId = (int) $root->id;
$ownerId = (int) $root->userid;
$ownerName = '';
try {
$ownerName = self::plainText((string) (User::find($ownerId)?->user_name ?? ''), 80);
} catch (\Throwable $exception) {
// A missing user projection must not suppress the ticket alert.
}
$owner = $ownerName === '' ? 'UID ' . $ownerId : $ownerName . '(UID ' . $ownerId . ')';
$instanceName = '';
$instanceId = (int) ($root->instance_id ?? 0);
if ($instanceId > 0) {
try {
$instance = CloudInstance::where('id', $instanceId)
->where('user_id', $ownerId)->first();
$instanceName = self::plainText((string) ($instance?->name ?? ''), 100);
} catch (\Throwable $exception) {
// Ticket notifications remain available if the instance projection is unavailable.
}
}
$label = $event->kind === 'created' ? '🆕 新工单' : '💬 用户回复';
$type = [
'pre_sales' => '售前',
'after_sales' => '售后',
'technical' => '技术支持',
'finance' => '财务',
][(string) ($root->ticket_type ?? '')] ?? '技术支持';
$priority = [
'high' => '高',
'medium' => '中',
'low' => '低',
][(string) ($root->priority ?? '')] ?? '中';
$status = (int) ($root->status ?? 0) === 1 ? '等待管理员' : '已关闭';
$timestamp = (int) ($message->datetime ?? time());
$adminUrl = rtrim((string) Config::get('baseUrl'), '/')
. '/admin/ticket/' . $ticketId . '/view';
$title = self::plainText((string) $root->title, 180);
$content = self::plainText((string) $message->content, 2500, true);
$attachments = count($event->result->attachments);
$lines = [
$label . ' #' . $ticketId,
'',
'主题:' . ($title === '' ? '未命名工单' : $title),
'用户:' . $owner,
'分类:' . $type,
'优先级:' . $priority,
'状态:' . $status,
];
if ($instanceName !== '') {
$lines[] = '关联实例:' . $instanceName;
}
$lines[] = '提交时间:' . gmdate('Y-m-d H:i:s', $timestamp) . ' UTC';
$lines[] = '';
$lines[] = '用户内容:';
$lines[] = $content === '' ? '(无文本内容)' : $content;
if ($attachments > 0) {
$lines[] = '';
$lines[] = '附件:' . $attachments . ' 个,请在后台查看';
}
$lines[] = '后台地址:' . $adminUrl;
$lines[] = '';
$lines[] = (int) ($root->status ?? 0) === 1
? '↩️ 直接回复本消息即可回复用户'
: '工单已关闭,请在管理后台查看';
return mb_substr(implode("\n", $lines), 0, 4096, 'UTF-8');
}
private static function plainText(string $value, int $limit, bool $multiline = false): string
{
$value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$value = str_replace(["\r\n", "\r"], "\n", $value);
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value) ?? '';
if ($multiline) {
$value = preg_replace('/[ \t]+/u', ' ', $value) ?? '';
$value = preg_replace('/\n{3,}/u', "\n\n", $value) ?? '';
} else {
$value = preg_replace('/\s+/u', ' ', $value) ?? '';
}
return mb_substr(trim($value), 0, $limit, 'UTF-8');
}
public static function registerWebhook(): bool
{
try {
$config = TicketTelegramConfig::runtime(true);
} catch (\Throwable $exception) {
throw new \RuntimeException(self::safeConfigurationMessage($exception));
}
try {
$result = (new BotApi($config['bot_token']))->call('setWebhook', [
'url' => $config['webhook_base_url'] . '/telegram_callback',
'secret_token' => $config['webhook_secret'],
'allowed_updates' => '["message"]',
], 10);
if ($result !== true) {
throw new \RuntimeException('Webhook registration rejected');
}
return true;
} catch (\Throwable $exception) {
throw new \RuntimeException('Telegram webhook 注册失败,请检查 HTTPS、出站网络和 bot 配置');
}
}
private static function readState($row): array
{
$state = $row === null ? [] : json_decode((string) $row->value, true);
return is_array($state) ? $state : [];
}
private static function sendBindingConfirmation(string $chatId): void
{
try {
$config = TicketTelegramConfig::runtime(true);
(new BotApi($config['bot_token']))->call('sendMessage', [
'chat_id' => $chatId,
'text' => "绑定成功\n此 Telegram 账号已绑定为管理员工单提醒接收账号。",
'disable_web_page_preview' => 'true',
], 10);
} catch (\Throwable $exception) {
// SDK error URLs may contain bot secrets. Never log their messages.
error_log('Administrator Telegram binding confirmation failed');
}
}
private static function safeConfigurationMessage(\Throwable $exception): string
{
$message = $exception->getMessage();
foreach ([
'Telegram 工单提醒',
'Telegram 凭据',
'Telegram 机器人 Token',
'Telegram Webhook 密钥',
'Telegram 通信域名',
'PHP sodium ',
'请在工单系统的 Telegram ',
] as $safePrefix) {
if (str_starts_with($message, $safePrefix)) {
return $message;
}
}
return 'Telegram 配置读取失败,请检查数据库与服务器日志';
}
private static function eligibleAdmin(int $adminId): bool
{
$allowed = array_map('intval', explode(',', (string) Config::get('super_admin', '')));
if ($adminId <= 0 || !in_array($adminId, $allowed, true)) {
return false;
}
$user = User::find($adminId);
return $user !== null && (bool) $user->is_admin && (int) $user->enable === 1;
}
}