TelegramChannelService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Database\Query\Builder;
  4. use Illuminate\Support\Facades\Crypt;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Facades\Validator;
  9. use Illuminate\Validation\ValidationException;
  10. use RuntimeException;
  11. use Telegram\Bot\Api;
  12. use Telegram\Bot\Exceptions\TelegramResponseException;
  13. use Telegram\Bot\FileUpload\InputFile;
  14. class TelegramChannelService
  15. {
  16. public const LEGACY_FIELD = 'channel_message';
  17. public const VIEW = 'admin/telegramChannel/list';
  18. public const MANAGE = 'admin/telegramChannel/save';
  19. public const PUBLISH = 'admin/telegramChannel/publish';
  20. public function list(): array
  21. {
  22. return $this->joinedChannels()->orderBy('channels.id')
  23. ->get()
  24. ->map(fn ($row) => $this->present($row, (int) $row->default_channel_id === (int) $row->id))
  25. ->all();
  26. }
  27. public function detail(int $id): array
  28. {
  29. $row = $this->find($id);
  30. return $this->present($row, (int) $row->default_channel_id === $id, true);
  31. }
  32. public function save(#[\SensitiveParameter] array $input, bool $legacy = false): array
  33. {
  34. if (is_string($input['name'] ?? null)) {
  35. $input['name'] = trim($input['name']);
  36. if ($input['name'] === '') {
  37. $input['name'] = null;
  38. }
  39. }
  40. $hasMessage = array_intersect(['type', 'text', 'image', 'video', 'button'], array_keys($input)) !== [];
  41. $fields = Validator::make($input, [
  42. 'id' => $legacy ? 'prohibited' : 'sometimes|required|integer|min:1',
  43. 'name' => 'nullable|string|max:255',
  44. 'chatId' => 'required|string|max:64',
  45. 'bot_id' => 'sometimes|nullable|integer|min:1|prohibits:bot_token',
  46. 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
  47. 'bot_token' => ['nullable', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
  48. 'enabled' => 'sometimes|required|boolean',
  49. 'type' => [($legacy || $hasMessage) ? 'required' : 'sometimes', 'string', 'in:text,image,video'],
  50. ], [], ['name' => '频道名称'])->validate();
  51. $target = self::normalizeTarget($fields['chatId']);
  52. if ($target === null) {
  53. throw ValidationException::withMessages(['chatId' => '请输入频道用户名或负数频道 ID']);
  54. }
  55. $message = isset($fields['type']) ? self::message($input) : null;
  56. $row = isset($fields['id']) && !$legacy ? $this->find((int) $fields['id']) : null;
  57. if ($legacy) {
  58. $row = $this->joinedChannels()->where(fn (Builder $query) => $query
  59. ->where('channels.target', $target)->orWhere('channels.telegram_chat_id', $target))->first();
  60. }
  61. $newToken = $fields['bot_token'] ?? null;
  62. $botId = array_key_exists('bot_id', $fields) ? $fields['bot_id'] : $row?->bot_id;
  63. $selectedBot = $botId === null ? null : $this->findBot((int) $botId);
  64. $bot = $newToken === null ? [] : $this->validateBot($fields['bot_username'] ?? null, $newToken);
  65. if ($newToken === null && isset($fields['bot_username'])
  66. && strcasecmp(ltrim($fields['bot_username'], '@'), $selectedBot->bot_username ?? '') !== 0) {
  67. throw ValidationException::withMessages(['bot_username' => '请从机器人管理中选择机器人']);
  68. }
  69. $targetUnchanged = $row !== null && in_array($target, [$row->target, $row->telegram_chat_id], true);
  70. $unbound = !$legacy && $botId === null && $newToken === null;
  71. $bindingUnchanged = (int) $botId === (int) $row?->bot_id && $newToken === null;
  72. if ($targetUnchanged && ($bindingUnchanged || $unbound)) {
  73. $identity = ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name];
  74. } elseif ($unbound) {
  75. $identity = ['target' => $target, 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null, 'title' => ltrim($target, '@')];
  76. } else {
  77. $identity = $this->resolve($target, $newToken ?? $this->storedToken($selectedBot));
  78. }
  79. return DB::transaction(function () use ($fields, $identity, $message, $legacy, $row, $bot, $selectedBot) {
  80. $default = $this->settings()->lockForUpdate()->first();
  81. $channels = DB::table('telegram_channels');
  82. $existing = $row === null ? null : (clone $channels)->where('id', $row->id)->first();
  83. if ($row !== null && ($existing === null || $existing->target !== $row->target
  84. || $existing->telegram_chat_id !== $row->telegram_chat_id || $existing->bot_id !== $row->bot_id)) {
  85. throw ValidationException::withMessages(['id' => '频道已变更,请刷新后重试']);
  86. }
  87. $match = (clone $channels)->where(function (Builder $query) use ($identity) {
  88. $query->where('target', $identity['target']);
  89. if ($identity['telegram_chat_id'] !== null) {
  90. $query->orWhere('telegram_chat_id', $identity['telegram_chat_id']);
  91. }
  92. })->get();
  93. if ($legacy && $row === null && $match->count() === 1) {
  94. $existing = $match->first();
  95. if ($existing->bot_id !== null && $bot === [] && !array_key_exists('bot_id', $fields)) {
  96. throw ValidationException::withMessages(['chatId' => '请使用已保存的频道标识,或通过频道管理按 ID 编辑']);
  97. }
  98. }
  99. if ($match->contains(fn ($channel) => (int) $channel->id !== (int) $existing?->id)) {
  100. throw ValidationException::withMessages(['chatId' => '该频道已存在']);
  101. }
  102. if ($selectedBot !== null && $this->findBot((int) $selectedBot->id)->bot_token !== $selectedBot->bot_token) {
  103. throw ValidationException::withMessages(['bot_id' => '机器人配置已更新,请刷新后重试']);
  104. }
  105. $binding = $selectedBot?->id;
  106. if ($bot !== []) {
  107. $registered = DB::table('telegram_bots')->where('bot_username', $bot['bot_username'])->first();
  108. if ($registered !== null && $this->storedToken($registered) !== $this->storedToken((object) $bot)) {
  109. throw ValidationException::withMessages(['bot_token' => '请在机器人管理中更新已有机器人的 Token']);
  110. }
  111. $binding = $registered?->id ?? DB::table('telegram_bots')->insertGetId($bot + [
  112. 'created_at' => now(), 'updated_at' => now(),
  113. ]);
  114. }
  115. $enabled = (bool) ($fields['enabled'] ?? $existing?->enabled ?? true);
  116. $values = [
  117. 'name' => $fields['name'] ?? $existing?->name ?? $identity['title'],
  118. 'target' => $identity['target'],
  119. 'telegram_chat_id' => $identity['telegram_chat_id'],
  120. 'enabled' => $enabled,
  121. 'message' => $message === null
  122. ? ($existing?->message ?? 'null')
  123. : json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  124. 'bot_id' => $binding,
  125. 'updated_at' => now(),
  126. ];
  127. if ($existing === null) {
  128. $firstLegacy = $legacy && !$channels->exists();
  129. $id = (int) $channels->insertGetId($values + ['created_at' => now()]);
  130. if ($firstLegacy && $enabled) {
  131. $this->settings()->update(['default_channel_id' => $id]);
  132. }
  133. } else {
  134. $id = (int) $existing->id;
  135. $channels->where('id', $id)->update($values);
  136. if (!$enabled && (int) $default->default_channel_id === $id) {
  137. $this->settings()->update(['default_channel_id' => null]);
  138. }
  139. }
  140. return $this->detail($id);
  141. }, 3);
  142. }
  143. public function delete(int $id): void
  144. {
  145. DB::transaction(function () use ($id) {
  146. $default = $this->settings()->lockForUpdate()->first();
  147. $this->find($id);
  148. if ((int) $default->default_channel_id === $id) {
  149. $this->settings()->update(['default_channel_id' => null]);
  150. }
  151. DB::table('telegram_channels')->where('id', $id)->delete();
  152. }, 3);
  153. }
  154. public function legacyMessage(): ?array
  155. {
  156. $row = $this->defaultChannel();
  157. return $row === null ? null : ['chatId' => ltrim($row->target, '@')] + $this->storedMessage($row);
  158. }
  159. public function roomNoticeTarget(): ?string
  160. {
  161. $row = $this->defaultChannel();
  162. return $row === null ? null : ($row->telegram_chat_id ?? $row->target);
  163. }
  164. public function publish(int $id, bool $pin): array
  165. {
  166. $row = $this->find($id);
  167. return $this->publishContent($row, $this->storedMessage($row), $pin);
  168. }
  169. public function publishMessage(int $id, array $message, bool $pin, string $target): array
  170. {
  171. $row = $this->find($id);
  172. if ($row->bot_id === null) {
  173. throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
  174. }
  175. if (($row->telegram_chat_id ?? $row->target) !== $target) {
  176. throw ValidationException::withMessages(['channel_id' => '频道标识已变更,请重新创建发送记录']);
  177. }
  178. return $this->publishContent($row, $message, $pin);
  179. }
  180. private function publishContent(object $row, array $message, bool $pin): array
  181. {
  182. $channel = $this->present($row, false) + $message;
  183. if (!$channel['enabled']) {
  184. throw ValidationException::withMessages(['id' => '请先启用频道']);
  185. }
  186. if ($channel['type'] === null) {
  187. throw ValidationException::withMessages(['type' => '请先保存要发布的消息']);
  188. }
  189. $params = ['chat_id' => $channel['telegram_chat_id'] ?? $channel['chatId']];
  190. if ($channel['button'] !== []) {
  191. $params['reply_markup'] = json_encode(['inline_keyboard' => $channel['button']], JSON_THROW_ON_ERROR);
  192. }
  193. try {
  194. $telegram = $this->telegram($this->storedToken($row));
  195. $response = $this->send($telegram, $channel, $params);
  196. } catch (TelegramResponseException $exception) {
  197. if (($exception->getHttpStatusCode() ?? 500) < 500) {
  198. return ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => 'Telegram 拒绝发布,请检查机器人发帖权限、频道和消息内容'];
  199. }
  200. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  201. } catch (\Exception) {
  202. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  203. }
  204. $messageId = $response['message_id'] ?? null;
  205. if ($messageId === null) {
  206. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  207. }
  208. $pinned = null;
  209. $error = null;
  210. if ($pin) {
  211. try {
  212. $pinned = $telegram->pinChatMessage(['chat_id' => $params['chat_id'], 'message_id' => $messageId]);
  213. if (!$pinned) {
  214. $error = '消息已发布,置顶未成功';
  215. }
  216. } catch (\Exception) {
  217. $pinned = false;
  218. $error = '消息已发布,请在频道中检查置顶状态';
  219. }
  220. }
  221. return ['sent' => true, 'pinned' => $pinned, 'message_id' => $messageId, 'error' => $error];
  222. }
  223. private function send(Api $telegram, array $channel, array $params): array
  224. {
  225. if ($channel['type'] === 'text') {
  226. return $telegram->post('sendMessage', $params + ['text' => $channel['text']])->getResult() ?: [];
  227. }
  228. $image = $channel['type'] === 'image';
  229. $media = $channel[$channel['type']];
  230. $field = $image ? 'photo' : 'video';
  231. $params['caption'] = $channel['text'];
  232. // Only read files produced by the admin upload endpoints on the configured public disk.
  233. $disk = Storage::disk('public');
  234. $prefix = rtrim($disk->url(''), '/') . '/';
  235. $path = str_starts_with($media, $prefix) ? substr($media, strlen($prefix)) : '';
  236. if (preg_match('~\A(?:images|videos)/[a-f0-9]{32}\.(?:jpg|jpeg|png|webp|mp4|mov|avi|webm)\z~i', $path) && $disk->exists($path)) {
  237. $stream = $disk->readStream($path);
  238. if (!is_resource($stream)) {
  239. throw new RuntimeException('Unable to read uploaded media');
  240. }
  241. try {
  242. $params[$field] = InputFile::create($stream, basename($path));
  243. $response = $image ? $telegram->sendPhoto($params) : $telegram->sendVideo($params);
  244. return ['message_id' => $response->get('message_id')];
  245. } finally {
  246. if (is_resource($stream)) {
  247. fclose($stream);
  248. }
  249. }
  250. }
  251. // Telegram fetches external media directly.
  252. return $telegram->post($image ? 'sendPhoto' : 'sendVideo', $params + [$field => $media])->getResult() ?: [];
  253. }
  254. public function bots(): array
  255. {
  256. return DB::table('telegram_bots')->orderBy('bot_username')
  257. ->get(['id', 'bot_username', 'bot_name'])->all();
  258. }
  259. public function saveBot(#[\SensitiveParameter] array $input): array
  260. {
  261. $fields = Validator::make($input, [
  262. 'id' => 'sometimes|required|integer|min:1',
  263. 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
  264. 'bot_token' => ['required', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
  265. ])->validate();
  266. $id = isset($fields['id']) ? (int) $fields['id'] : null;
  267. $row = $id === null ? null : $this->findBot($id);
  268. $bot = $this->validateBot($fields['bot_username'] ?? $row?->bot_username, $fields['bot_token']);
  269. if ($row !== null && strcasecmp($row->bot_username, $bot['bot_username']) !== 0) {
  270. throw ValidationException::withMessages(['bot_username' => '请使用此机器人的 Token,更换机器人请新增后再绑定']);
  271. }
  272. return DB::transaction(function () use ($id, $row, $bot) {
  273. $this->settings()->lockForUpdate()->first();
  274. $bots = DB::table('telegram_bots');
  275. $duplicate = (clone $bots)->where('bot_username', $bot['bot_username'])->value('id');
  276. if ($duplicate !== null && (int) $duplicate !== $id) {
  277. throw ValidationException::withMessages(['bot_username' => '该机器人已存在']);
  278. }
  279. $values = $bot + ['updated_at' => now()];
  280. if ($id === null) {
  281. $id = (int) $bots->insertGetId($values + ['created_at' => now()]);
  282. } else {
  283. if ($this->findBot($id)->bot_token !== $row->bot_token) {
  284. throw ValidationException::withMessages(['id' => '机器人已更新,请刷新后重试']);
  285. }
  286. $bots->where('id', $id)->update($values);
  287. }
  288. return ['id' => $id, 'bot_username' => $bot['bot_username'], 'bot_name' => $bot['bot_name']];
  289. }, 3);
  290. }
  291. public function deleteBot(int $id): void
  292. {
  293. DB::transaction(function () use ($id) {
  294. $this->settings()->lockForUpdate()->first();
  295. $this->findBot($id);
  296. if (DB::table('telegram_channels')->where('bot_id', $id)->exists()) {
  297. throw ValidationException::withMessages(['id' => '机器人仍绑定频道,请先在频道中解除绑定']);
  298. }
  299. DB::table('telegram_bots')->where('id', $id)->delete();
  300. }, 3);
  301. }
  302. public function privateMenu(int $id, string $language): array
  303. {
  304. return $this->privateMenus($id)[$language] ?? ['reply' => '', 'buttons' => [], 'type' => 'text', 'image' => '', 'video' => ''];
  305. }
  306. public function privateMenus(int $id): array
  307. {
  308. $menus = json_decode($this->findBot($id)->private_menus ?? '{}', true);
  309. foreach ($menus as &$menu) {
  310. $menu += ['type' => 'text', 'image' => '', 'video' => ''];
  311. }
  312. return $menus;
  313. }
  314. public function savePrivateMenu(int $id, string $language, array $input): array
  315. {
  316. return $this->savePrivateMenus($id, [$language => $input])[$language];
  317. }
  318. public function savePrivateMenus(int $id, array $input): array
  319. {
  320. $menus = [];
  321. foreach ($input as $language => $menu) {
  322. $menus[$language] = $this->validatePrivateMenu($menu);
  323. }
  324. DB::transaction(function () use ($id, $menus) {
  325. $bot = DB::table('telegram_bots')->where('id', $id)->lockForUpdate()->first()
  326. ?? throw ValidationException::withMessages(['id' => '机器人不存在']);
  327. $existing = json_decode($bot->private_menus ?? '{}', true);
  328. DB::table('telegram_bots')->where('id', $id)->update([
  329. 'private_menus' => json_encode(array_replace($existing, $menus), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  330. 'updated_at' => now(),
  331. ]);
  332. }, 3);
  333. return $menus;
  334. }
  335. private function validatePrivateMenu(array $input): array
  336. {
  337. $menu = Validator::make($input, [
  338. 'buttons' => 'present|array|list|max:20',
  339. 'buttons.*' => 'required|array|list',
  340. 'buttons.*.*' => 'required|string|max:128',
  341. ])->validate();
  342. $content = self::message([
  343. 'type' => $input['type'] ?? 'text',
  344. 'text' => $input['reply'] ?? null,
  345. 'image' => $input['image'] ?? null,
  346. 'video' => $input['video'] ?? null,
  347. ]);
  348. $menu += [
  349. 'type' => $content['type'],
  350. 'reply' => $content['text'],
  351. 'image' => $content['type'] === 'image' ? $content['image'] : '',
  352. 'video' => $content['type'] === 'video' ? $content['video'] : '',
  353. ];
  354. return $menu;
  355. }
  356. public function registerPrivateWebhook(int $id): array
  357. {
  358. $bot = $this->findBot($id);
  359. $token = $this->storedToken($bot);
  360. if ($token === config('services.telegram.token')) {
  361. return ['system_bot' => true];
  362. }
  363. $secret = $bot->webhook_secret;
  364. if ($secret === null) {
  365. DB::table('telegram_bots')->where('id', $id)->whereNull('webhook_secret')
  366. ->update(['webhook_secret' => bin2hex(random_bytes(32))]);
  367. $bot = $this->findBot($id);
  368. $secret = $bot->webhook_secret;
  369. }
  370. $webhookUrl = rtrim((string) config('app.url'), '/') . '/api/telegramBot/' . $id . '/webhook';
  371. try {
  372. $telegram = $this->telegram($token);
  373. $existingUrl = (string) $telegram->getWebhookInfo()->get('url');
  374. } catch (\Exception) {
  375. throw ValidationException::withMessages(['id' => '无法读取 Telegram 接入状态,请检查 Bot Token']);
  376. }
  377. if ($existingUrl !== '' && $existingUrl !== $webhookUrl) {
  378. throw ValidationException::withMessages(['id' => '机器人已接入其他 Webhook,请确认停用原接入后重试']);
  379. }
  380. try {
  381. $registered = $telegram->setWebhook([
  382. 'url' => $webhookUrl,
  383. 'secret_token' => $secret,
  384. 'allowed_updates' => ['message'],
  385. ]);
  386. } catch (\Exception) {
  387. $registered = false;
  388. }
  389. if (!$registered) {
  390. throw ValidationException::withMessages(['id' => '无法接入 Telegram,请检查 Bot Token 和站点 HTTPS 配置']);
  391. }
  392. return ['system_bot' => false];
  393. }
  394. public function handlePrivateWebhook(int $id, string $secret, array $update): void
  395. {
  396. $bot = DB::table('telegram_bots')->where('id', $id)->first();
  397. abort_unless($bot?->webhook_secret && hash_equals($bot->webhook_secret, $secret), 404);
  398. if (is_int($update['update_id'] ?? null)) {
  399. rescue(fn () => Log::channel('telegram_webhook')->info('Telegram 收到更新', ['bot_id' => $id, 'update' => $update]));
  400. }
  401. $message = $update['message'] ?? [];
  402. $chatId = $message['chat']['id'] ?? null;
  403. if (($message['chat']['type'] ?? null) !== 'private' || !is_int($chatId)
  404. || !is_string($message['text'] ?? null) || !preg_match('/^\/start(?:\s|$)/D', $message['text'])) {
  405. return;
  406. }
  407. $language = strtolower(substr((string) ($message['from']['language_code'] ?? ''), 0, 2));
  408. $menu = $this->configuredPrivateMenu($bot, $language);
  409. if ($menu === null) {
  410. return;
  411. }
  412. try {
  413. $this->sendPrivateMenu($this->telegram($this->storedToken($bot)), $chatId, $menu);
  414. } catch (\Exception) {
  415. Log::warning('Telegram 私聊菜单发送失败', ['bot_id' => $id]);
  416. abort(503);
  417. }
  418. }
  419. public function sendSystemPrivateMenu($chatId, string $language): bool
  420. {
  421. $token = config('services.telegram.token');
  422. if (!$token) {
  423. return false;
  424. }
  425. foreach (DB::table('telegram_bots')->whereNotNull('private_menus')->cursor() as $bot) {
  426. if ($token === $this->storedToken($bot) && ($menu = $this->configuredPrivateMenu($bot, $language)) !== null) {
  427. $this->sendPrivateMenu($this->telegram(null), $chatId, $menu);
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. private function configuredPrivateMenu(object $bot, string $language): ?array
  434. {
  435. $menus = json_decode($bot->private_menus ?? '{}', true);
  436. return $menus[$language] ?? $menus['en'] ?? $menus['zh'] ?? ($menus['vi'] ?? null);
  437. }
  438. private function sendPrivateMenu(Api $telegram, $chatId, array $menu): void
  439. {
  440. $keyboard = $menu['buttons'] === []
  441. ? ['remove_keyboard' => true]
  442. : ['keyboard' => $menu['buttons'], 'resize_keyboard' => true];
  443. $this->send($telegram, ['text' => $menu['reply']] + $menu + ['type' => 'text'], [
  444. 'chat_id' => $chatId,
  445. 'reply_markup' => json_encode($keyboard, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  446. ]);
  447. }
  448. private function findBot(int $id): object
  449. {
  450. return DB::table('telegram_bots')->where('id', $id)->first()
  451. ?? throw ValidationException::withMessages(['bot_id' => '机器人不存在']);
  452. }
  453. private function validateBot(?string $username, #[\SensitiveParameter] string $token): array
  454. {
  455. try {
  456. $bot = $this->telegram($token)->getMe();
  457. } catch (\Exception) {
  458. throw ValidationException::withMessages(['bot_token' => '无法验证 Bot Token,请检查 Token 或 Telegram 连接']);
  459. }
  460. $actualUsername = $bot->get('username');
  461. if (!$bot->get('is_bot') || !is_string($actualUsername) || $actualUsername === '') {
  462. throw ValidationException::withMessages(['bot_token' => 'Bot Token 未返回有效的机器人账号']);
  463. }
  464. if ($username !== null && strcasecmp(ltrim($username, '@'), $actualUsername) !== 0) {
  465. throw ValidationException::withMessages(['bot_username' => '机器人用户名和 Bot Token 不匹配']);
  466. }
  467. return [
  468. 'bot_username' => strtolower($actualUsername),
  469. 'bot_name' => mb_substr((string) $bot->get('first_name'), 0, 255),
  470. 'bot_token' => Crypt::encryptString($token),
  471. ];
  472. }
  473. private function storedToken(?object $row): ?string
  474. {
  475. return $row?->bot_token === null ? null : Crypt::decryptString($row->bot_token);
  476. }
  477. protected function telegram(#[\SensitiveParameter] ?string $token): Api
  478. {
  479. return $token === null ? app(Api::class) : new Api($token);
  480. }
  481. private function resolve(string $target, #[\SensitiveParameter] ?string $token): array
  482. {
  483. if ($token === null && !config('services.telegram.token')) {
  484. throw ValidationException::withMessages(['bot_id' => '系统机器人尚未配置,请选择已添加的机器人']);
  485. }
  486. try {
  487. $chat = $this->telegram($token)->getChat(['chat_id' => $target]);
  488. } catch (\Exception) {
  489. $bot = $token === null ? '系统机器人' : '所选机器人';
  490. throw ValidationException::withMessages(['chatId' => "无法读取频道,请检查频道标识,并确认{$bot}已加入目标频道"]);
  491. }
  492. $id = (string) $chat->get('id');
  493. if ($chat->get('type') !== 'channel' || !preg_match('/^-[1-9]\d{1,19}$/D', $id)) {
  494. throw ValidationException::withMessages(['chatId' => '请输入 Telegram 频道,群组和私聊无法使用']);
  495. }
  496. $username = $chat->get('username');
  497. return [
  498. 'target' => $username ? self::normalizeTarget($username) ?? $id : $id,
  499. 'telegram_chat_id' => $id,
  500. 'title' => mb_substr((string) ($chat->get('title') ?: $target), 0, 255),
  501. ];
  502. }
  503. public static function legacyChannel(mixed $value): ?array
  504. {
  505. if (!is_array($value) || ($target = self::normalizeTarget($value['chatId'] ?? null)) === null) {
  506. return null;
  507. }
  508. $value['type'] ??= !empty($value['video']) ? 'video' : (!empty($value['image']) ? 'image' : 'text');
  509. try {
  510. $message = self::message($value);
  511. } catch (ValidationException) {
  512. return null;
  513. }
  514. return [
  515. 'name' => ltrim($target, '@'),
  516. 'target' => $target,
  517. 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null,
  518. 'enabled' => true,
  519. 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  520. ];
  521. }
  522. private static function normalizeTarget(mixed $value): ?string
  523. {
  524. if (!is_string($value)) {
  525. return null;
  526. }
  527. $value = trim($value);
  528. if (preg_match('/^-[1-9]\d{1,19}$/D', $value)) {
  529. return $value;
  530. }
  531. return preg_match('/^@?[a-z][a-z0-9_]{3,31}$/iD', $value) ? '@' . strtolower(ltrim($value, '@')) : null;
  532. }
  533. public static function message(array $input): array
  534. {
  535. $data = Validator::make($input, [
  536. 'type' => 'required|in:text,image,video',
  537. 'text' => 'nullable|required_if:type,text|string|max:' . (($input['type'] ?? null) === 'text' ? 4096 : 1024),
  538. 'image' => 'nullable|required_if:type,image|string|max:2048|url:http,https',
  539. 'video' => 'nullable|required_if:type,video|string|max:2048|url:http,https',
  540. 'button' => 'sometimes|array|list',
  541. 'button.*' => 'required|array|list',
  542. 'button.*.*' => 'required|array',
  543. 'button.*.*.text' => 'required|string',
  544. 'button.*.*.url' => 'required|string|url:http,https,tg',
  545. ])->validate();
  546. foreach (['image', 'video'] as $field) {
  547. $url = $data[$field] ?? '';
  548. $host = rtrim(strtolower(trim(parse_url($url, PHP_URL_HOST) ?? '', '[]')), '.');
  549. if ($url !== '' && (
  550. parse_url($url, PHP_URL_USER) !== null
  551. || $host === 'localhost'
  552. || str_ends_with($host, '.localhost')
  553. || (filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE))
  554. || str_contains(strtolower(rawurldecode(parse_url($url, PHP_URL_PATH) ?? '')), '/_ignition/')
  555. )) {
  556. throw ValidationException::withMessages([$field => '媒体地址须可公开访问']);
  557. }
  558. }
  559. return [
  560. 'type' => $data['type'],
  561. 'text' => $data['text'] ?? '',
  562. 'image' => $data['image'] ?? '',
  563. 'video' => $data['video'] ?? '',
  564. 'button' => array_map(fn ($row) => array_map(
  565. fn ($button) => ['text' => $button['text'], 'url' => $button['url']],
  566. $row,
  567. ), $data['button'] ?? []),
  568. ];
  569. }
  570. private function settings(): Builder
  571. {
  572. return DB::table('telegram_channel_settings')->where('id', 1);
  573. }
  574. private function defaultChannel(): ?object
  575. {
  576. return $this->joinedChannels()->where('channels.enabled', true)
  577. ->whereColumn('channels.id', 'settings.default_channel_id')->first();
  578. }
  579. private function find(int $id): object
  580. {
  581. return $this->joinedChannels()->where('channels.id', $id)->first()
  582. ?? throw ValidationException::withMessages(['id' => '频道不存在']);
  583. }
  584. private function joinedChannels(): Builder
  585. {
  586. return DB::table('telegram_channels as channels')
  587. ->crossJoin('telegram_channel_settings as settings')
  588. ->leftJoin('telegram_bots as bots', 'bots.id', '=', 'channels.bot_id')
  589. ->select('channels.id', 'channels.name', 'channels.target', 'channels.telegram_chat_id', 'channels.enabled', 'channels.message', 'channels.bot_id', 'settings.default_channel_id', 'bots.bot_username', 'bots.bot_name', 'bots.bot_token')
  590. ->where('settings.id', 1);
  591. }
  592. private function present(object $row, bool $default, bool $withMessage = false): array
  593. {
  594. $data = [
  595. 'id' => (int) $row->id,
  596. 'name' => $row->name,
  597. 'chatId' => $row->target,
  598. 'telegram_chat_id' => $row->telegram_chat_id,
  599. 'bot_id' => $row->bot_id === null ? null : (int) $row->bot_id,
  600. 'bot_username' => $row->bot_username,
  601. 'bot_name' => $row->bot_name,
  602. 'has_bot_token' => $row->bot_token !== null,
  603. 'enabled' => (bool) $row->enabled,
  604. 'is_default' => $default,
  605. ];
  606. return $withMessage ? $data + $this->storedMessage($row) : $data;
  607. }
  608. private function storedMessage(object $row): array
  609. {
  610. return json_decode($row->message, true) ?? [
  611. 'type' => null,
  612. 'text' => '',
  613. 'image' => '',
  614. 'video' => '',
  615. 'button' => [],
  616. ];
  617. }
  618. }