TelegramChannelService.php 29 KB

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