| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425 |
- <?php
- namespace App\Services;
- use Illuminate\Database\Query\Builder;
- use Illuminate\Support\Facades\Crypt;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Validation\ValidationException;
- use RuntimeException;
- use Telegram\Bot\Api;
- use Telegram\Bot\Exceptions\TelegramResponseException;
- use Telegram\Bot\FileUpload\InputFile;
- class TelegramChannelService
- {
- public const LEGACY_FIELD = 'channel_message';
- public const VIEW = 'admin/telegramChannel/list';
- public const MANAGE = 'admin/telegramChannel/save';
- public const PUBLISH = 'admin/telegramChannel/publish';
- public function list(): array
- {
- return $this->joinedChannels()->orderBy('channels.id')
- ->get()
- ->map(fn ($row) => $this->present($row, (int) $row->default_channel_id === (int) $row->id))
- ->all();
- }
- public function detail(int $id): array
- {
- $row = $this->find($id);
- return $this->present($row, (int) $row->default_channel_id === $id, true);
- }
- public function save(#[\SensitiveParameter] array $input, bool $legacy = false): array
- {
- $hasMessage = array_intersect(['type', 'text', 'image', 'video', 'button'], array_keys($input)) !== [];
- $fields = Validator::make($input, [
- 'id' => $legacy ? 'prohibited' : 'sometimes|required|integer|min:1',
- 'name' => 'sometimes|required|string|max:255',
- 'chatId' => 'required|string|max:64',
- 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
- 'bot_token' => ['nullable', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
- 'enabled' => 'sometimes|required|boolean',
- 'type' => [($legacy || $hasMessage) ? 'required' : 'sometimes', 'string', 'in:text,image,video'],
- ])->validate();
- $target = self::normalizeTarget($fields['chatId']);
- if ($target === null) {
- throw ValidationException::withMessages(['chatId' => '请输入频道用户名或负数频道 ID']);
- }
- $message = isset($fields['type']) ? self::message($input) : null;
- $row = isset($fields['id']) && !$legacy ? $this->find((int) $fields['id']) : null;
- if ($legacy) {
- $row = DB::table('telegram_channels')->where('target', $target)->orWhere('telegram_chat_id', $target)->first();
- }
- $newToken = $fields['bot_token'] ?? null;
- $bot = $this->validateBot($fields['bot_username'] ?? null, $newToken, $row);
- $targetUnchanged = $row !== null && in_array($target, [$row->target, $row->telegram_chat_id], true);
- $identity = $targetUnchanged && $newToken === null
- ? ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name]
- : $this->resolve($target, $newToken ?? $this->storedToken($row));
- return DB::transaction(function () use ($fields, $identity, $message, $legacy, $row, $bot) {
- $default = $this->settings()->lockForUpdate()->first();
- $channels = DB::table('telegram_channels');
- $existing = $row === null ? null : (clone $channels)->where('id', $row->id)->first();
- if ($row !== null && ($existing === null || $existing->target !== $row->target
- || $existing->telegram_chat_id !== $row->telegram_chat_id || $existing->bot_token !== $row->bot_token)) {
- throw ValidationException::withMessages(['id' => '频道已变更,请刷新后重试']);
- }
- $match = (clone $channels)->where(function (Builder $query) use ($identity) {
- $query->where('target', $identity['target']);
- if ($identity['telegram_chat_id'] !== null) {
- $query->orWhere('telegram_chat_id', $identity['telegram_chat_id']);
- }
- })->get();
- if ($legacy && $row === null && $match->count() === 1) {
- $existing = $match->first();
- if ($existing->bot_token !== null && $bot === []) {
- throw ValidationException::withMessages(['chatId' => '请使用已保存的频道标识,或通过频道管理按 ID 编辑']);
- }
- }
- if ($match->contains(fn ($channel) => (int) $channel->id !== (int) $existing?->id)) {
- throw ValidationException::withMessages(['chatId' => '该频道已存在']);
- }
- $enabled = (bool) ($fields['enabled'] ?? $existing?->enabled ?? true);
- $values = [
- 'name' => $fields['name'] ?? $existing?->name ?? $identity['title'],
- 'target' => $identity['target'],
- 'telegram_chat_id' => $identity['telegram_chat_id'],
- 'enabled' => $enabled,
- 'message' => $message === null
- ? ($existing?->message ?? 'null')
- : json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
- 'updated_at' => now(),
- ] + $bot;
- if ($existing === null) {
- $firstLegacy = $legacy && !$channels->exists();
- $id = (int) $channels->insertGetId($values + ['created_at' => now()]);
- if ($firstLegacy && $enabled) {
- $this->settings()->update(['default_channel_id' => $id]);
- }
- } else {
- $id = (int) $existing->id;
- $channels->where('id', $id)->update($values);
- if (!$enabled && (int) $default->default_channel_id === $id) {
- $this->settings()->update(['default_channel_id' => null]);
- }
- }
- return $this->detail($id);
- }, 3);
- }
- public function setDefault(int $id): array
- {
- return DB::transaction(function () use ($id) {
- $this->settings()->lockForUpdate()->first();
- $row = $this->find($id);
- if (!$row->enabled) {
- throw ValidationException::withMessages(['id' => '请先启用频道']);
- }
- $this->settings()->update(['default_channel_id' => $id]);
- return $this->detail($id);
- }, 3);
- }
- public function delete(int $id): void
- {
- DB::transaction(function () use ($id) {
- $default = $this->settings()->lockForUpdate()->first();
- $this->find($id);
- if ((int) $default->default_channel_id === $id) {
- $this->settings()->update(['default_channel_id' => null]);
- }
- DB::table('telegram_channels')->where('id', $id)->delete();
- }, 3);
- }
- public function legacyMessage(): ?array
- {
- $row = $this->defaultChannel();
- return $row === null ? null : ['chatId' => ltrim($row->target, '@')] + $this->storedMessage($row);
- }
- public function roomNoticeTarget(): ?string
- {
- $row = $this->defaultChannel();
- return $row === null ? null : ($row->telegram_chat_id ?? $row->target);
- }
- public function publish(int $id, bool $pin): array
- {
- $row = $this->find($id);
- $channel = $this->present($row, (int) $row->default_channel_id === $id, true);
- if (!$channel['enabled']) {
- throw ValidationException::withMessages(['id' => '请先启用频道']);
- }
- if ($channel['type'] === null) {
- throw ValidationException::withMessages(['type' => '请先保存要发布的消息']);
- }
- $params = ['chat_id' => $channel['telegram_chat_id'] ?? $channel['chatId']];
- if ($channel['button'] !== []) {
- $params['reply_markup'] = json_encode(['inline_keyboard' => $channel['button']], JSON_THROW_ON_ERROR);
- }
- try {
- $telegram = $this->telegram($this->storedToken($row));
- $response = $this->send($telegram, $channel, $params);
- } catch (TelegramResponseException $exception) {
- if (($exception->getHttpStatusCode() ?? 500) < 500) {
- return ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => 'Telegram 拒绝发布,请检查机器人发帖权限、频道和消息内容'];
- }
- return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
- } catch (\Exception) {
- return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
- }
- $messageId = $response['message_id'] ?? null;
- if ($messageId === null) {
- return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
- }
- $pinned = null;
- $error = null;
- if ($pin) {
- try {
- $pinned = $telegram->pinChatMessage(['chat_id' => $params['chat_id'], 'message_id' => $messageId]);
- if (!$pinned) {
- $error = '消息已发布,置顶未成功';
- }
- } catch (\Exception) {
- $pinned = false;
- $error = '消息已发布,请在频道中检查置顶状态';
- }
- }
- return ['sent' => true, 'pinned' => $pinned, 'message_id' => $messageId, 'error' => $error];
- }
- private function send(Api $telegram, array $channel, array $params): array
- {
- if ($channel['type'] === 'text') {
- return $telegram->post('sendMessage', $params + ['text' => $channel['text']])->getResult() ?: [];
- }
- $image = $channel['type'] === 'image';
- $media = $channel[$channel['type']];
- $field = $image ? 'photo' : 'video';
- $params['caption'] = $channel['text'];
- // Only read files produced by the admin upload endpoints on the configured public disk.
- $disk = Storage::disk('public');
- $prefix = rtrim($disk->url(''), '/') . '/';
- $path = str_starts_with($media, $prefix) ? substr($media, strlen($prefix)) : '';
- if (preg_match('~\A(?:images|videos)/[a-f0-9]{32}\.(?:jpg|jpeg|png|webp|mp4|mov|avi|webm)\z~i', $path) && $disk->exists($path)) {
- $stream = $disk->readStream($path);
- if (!is_resource($stream)) {
- throw new RuntimeException('Unable to read uploaded media');
- }
- try {
- $params[$field] = InputFile::create($stream, basename($path));
- $response = $image ? $telegram->sendPhoto($params) : $telegram->sendVideo($params);
- return ['message_id' => $response->get('message_id')];
- } finally {
- if (is_resource($stream)) {
- fclose($stream);
- }
- }
- }
- // Telegram fetches external media directly.
- return $telegram->post($image ? 'sendPhoto' : 'sendVideo', $params + [$field => $media])->getResult() ?: [];
- }
- private function validateBot(?string $username, #[\SensitiveParameter] ?string $token, ?object $row): array
- {
- if ($token === null) {
- if ($username !== null && strcasecmp(ltrim($username, '@'), $row->bot_username ?? '') !== 0) {
- throw ValidationException::withMessages(['bot_token' => '绑定或更换机器人时请填写 Bot Token']);
- }
- return [];
- }
- try {
- $bot = $this->telegram($token)->getMe();
- } catch (\Exception) {
- throw ValidationException::withMessages(['bot_token' => '无法验证 Bot Token,请检查 Token 或 Telegram 连接']);
- }
- $actualUsername = $bot->get('username');
- if (!$bot->get('is_bot') || !is_string($actualUsername) || $actualUsername === '') {
- throw ValidationException::withMessages(['bot_token' => 'Bot Token 未返回有效的机器人账号']);
- }
- if ($username !== null && strcasecmp(ltrim($username, '@'), $actualUsername) !== 0) {
- throw ValidationException::withMessages(['bot_username' => '机器人用户名和 Bot Token 不匹配']);
- }
- return [
- 'bot_username' => $actualUsername,
- 'bot_name' => mb_substr((string) $bot->get('first_name'), 0, 255),
- 'bot_token' => Crypt::encryptString($token),
- ];
- }
- private function storedToken(?object $row): ?string
- {
- return $row?->bot_token === null ? null : Crypt::decryptString($row->bot_token);
- }
- protected function telegram(#[\SensitiveParameter] ?string $token): Api
- {
- return $token === null ? app(Api::class) : new Api($token);
- }
- private function resolve(string $target, #[\SensitiveParameter] ?string $token): array
- {
- try {
- $chat = $this->telegram($token)->getChat(['chat_id' => $target]);
- } catch (\Exception) {
- throw ValidationException::withMessages(['chatId' => '无法读取频道,请检查频道标识及机器人是否已加入']);
- }
- $id = (string) $chat->get('id');
- if ($chat->get('type') !== 'channel' || !preg_match('/^-[1-9]\d{1,19}$/D', $id)) {
- throw ValidationException::withMessages(['chatId' => '请输入 Telegram 频道,群组和私聊无法使用']);
- }
- $username = $chat->get('username');
- return [
- 'target' => $username ? self::normalizeTarget($username) ?? $id : $id,
- 'telegram_chat_id' => $id,
- 'title' => mb_substr((string) ($chat->get('title') ?: $target), 0, 255),
- ];
- }
- public static function legacyChannel(mixed $value): ?array
- {
- if (!is_array($value) || ($target = self::normalizeTarget($value['chatId'] ?? null)) === null) {
- return null;
- }
- $value['type'] ??= !empty($value['video']) ? 'video' : (!empty($value['image']) ? 'image' : 'text');
- try {
- $message = self::message($value);
- } catch (ValidationException) {
- return null;
- }
- return [
- 'name' => ltrim($target, '@'),
- 'target' => $target,
- 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null,
- 'enabled' => true,
- 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
- ];
- }
- private static function normalizeTarget(mixed $value): ?string
- {
- if (!is_string($value)) {
- return null;
- }
- $value = trim($value);
- if (preg_match('/^-[1-9]\d{1,19}$/D', $value)) {
- return $value;
- }
- return preg_match('/^@?[a-z][a-z0-9_]{3,31}$/iD', $value) ? '@' . strtolower(ltrim($value, '@')) : null;
- }
- private static function message(array $input): array
- {
- $data = Validator::make($input, [
- 'type' => 'required|in:text,image,video',
- 'text' => 'nullable|required_if:type,text|string|max:' . (($input['type'] ?? null) === 'text' ? 4096 : 1024),
- 'image' => 'nullable|required_if:type,image|string|max:2048|url:http,https',
- 'video' => 'nullable|required_if:type,video|string|max:2048|url:http,https',
- 'button' => 'sometimes|array|list',
- 'button.*' => 'required|array|list',
- 'button.*.*' => 'required|array',
- 'button.*.*.text' => 'required|string',
- 'button.*.*.url' => 'required|string|url:http,https,tg',
- ])->validate();
- foreach (['image', 'video'] as $field) {
- $url = $data[$field] ?? '';
- $host = rtrim(strtolower(trim(parse_url($url, PHP_URL_HOST) ?? '', '[]')), '.');
- if ($url !== '' && (
- parse_url($url, PHP_URL_USER) !== null
- || $host === 'localhost'
- || str_ends_with($host, '.localhost')
- || (filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE))
- || str_contains(strtolower(rawurldecode(parse_url($url, PHP_URL_PATH) ?? '')), '/_ignition/')
- )) {
- throw ValidationException::withMessages([$field => '媒体地址须可公开访问']);
- }
- }
- return [
- 'type' => $data['type'],
- 'text' => $data['text'] ?? '',
- 'image' => $data['image'] ?? '',
- 'video' => $data['video'] ?? '',
- 'button' => array_map(fn ($row) => array_map(
- fn ($button) => ['text' => $button['text'], 'url' => $button['url']],
- $row,
- ), $data['button'] ?? []),
- ];
- }
- private function settings(): Builder
- {
- return DB::table('telegram_channel_settings')->where('id', 1);
- }
- private function defaultChannel(): ?object
- {
- return $this->joinedChannels()->where('channels.enabled', true)
- ->whereColumn('channels.id', 'settings.default_channel_id')->first();
- }
- private function find(int $id): object
- {
- return $this->joinedChannels()->where('channels.id', $id)->first()
- ?? throw ValidationException::withMessages(['id' => '频道不存在']);
- }
- private function joinedChannels(): Builder
- {
- return DB::table('telegram_channels as channels')
- ->crossJoin('telegram_channel_settings as settings')
- ->select('channels.*', 'settings.default_channel_id')
- ->where('settings.id', 1);
- }
- private function present(object $row, bool $default, bool $withMessage = false): array
- {
- $data = [
- 'id' => (int) $row->id,
- 'name' => $row->name,
- 'chatId' => $row->target,
- 'telegram_chat_id' => $row->telegram_chat_id,
- 'bot_username' => $row->bot_username,
- 'bot_name' => $row->bot_name,
- 'has_bot_token' => $row->bot_token !== null,
- 'enabled' => (bool) $row->enabled,
- 'is_default' => $default,
- ];
- return $withMessage ? $data + $this->storedMessage($row) : $data;
- }
- private function storedMessage(object $row): array
- {
- return json_decode($row->message, true) ?? [
- 'type' => null,
- 'text' => '',
- 'image' => '',
- 'video' => '',
- 'button' => [],
- ];
- }
- }
|