TelegramChannelService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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\Validator;
  8. use Illuminate\Validation\ValidationException;
  9. use RuntimeException;
  10. use Telegram\Bot\Api;
  11. use Telegram\Bot\Exceptions\TelegramResponseException;
  12. use Telegram\Bot\FileUpload\InputFile;
  13. class TelegramChannelService
  14. {
  15. public const LEGACY_FIELD = 'channel_message';
  16. public const VIEW = 'admin/telegramChannel/list';
  17. public const MANAGE = 'admin/telegramChannel/save';
  18. public const PUBLISH = 'admin/telegramChannel/publish';
  19. public function list(): array
  20. {
  21. return $this->joinedChannels()->orderBy('channels.id')
  22. ->get()
  23. ->map(fn ($row) => $this->present($row, (int) $row->default_channel_id === (int) $row->id))
  24. ->all();
  25. }
  26. public function detail(int $id): array
  27. {
  28. $row = $this->find($id);
  29. return $this->present($row, (int) $row->default_channel_id === $id, true);
  30. }
  31. public function save(#[\SensitiveParameter] array $input, bool $legacy = false): array
  32. {
  33. $hasMessage = array_intersect(['type', 'text', 'image', 'video', 'button'], array_keys($input)) !== [];
  34. $fields = Validator::make($input, [
  35. 'id' => $legacy ? 'prohibited' : 'sometimes|required|integer|min:1',
  36. 'name' => 'sometimes|required|string|max:255',
  37. 'chatId' => 'required|string|max:64',
  38. 'bot_username' => ['nullable', 'string', 'max:64', 'regex:/^@?[a-z][a-z0-9_]*$/iD'],
  39. 'bot_token' => ['nullable', 'string', 'max:255', 'regex:/^[1-9][0-9]*:[a-z0-9_-]+$/iD'],
  40. 'enabled' => 'sometimes|required|boolean',
  41. 'type' => [($legacy || $hasMessage) ? 'required' : 'sometimes', 'string', 'in:text,image,video'],
  42. ])->validate();
  43. $target = self::normalizeTarget($fields['chatId']);
  44. if ($target === null) {
  45. throw ValidationException::withMessages(['chatId' => '请输入频道用户名或负数频道 ID']);
  46. }
  47. $message = isset($fields['type']) ? self::message($input) : null;
  48. $row = isset($fields['id']) && !$legacy ? $this->find((int) $fields['id']) : null;
  49. if ($legacy) {
  50. $row = DB::table('telegram_channels')->where('target', $target)->orWhere('telegram_chat_id', $target)->first();
  51. }
  52. $newToken = $fields['bot_token'] ?? null;
  53. $bot = $this->validateBot($fields['bot_username'] ?? null, $newToken, $row);
  54. $targetUnchanged = $row !== null && in_array($target, [$row->target, $row->telegram_chat_id], true);
  55. $identity = $targetUnchanged && $newToken === null
  56. ? ['target' => $row->target, 'telegram_chat_id' => $row->telegram_chat_id, 'title' => $row->name]
  57. : $this->resolve($target, $newToken ?? $this->storedToken($row));
  58. return DB::transaction(function () use ($fields, $identity, $message, $legacy, $row, $bot) {
  59. $default = $this->settings()->lockForUpdate()->first();
  60. $channels = DB::table('telegram_channels');
  61. $existing = $row === null ? null : (clone $channels)->where('id', $row->id)->first();
  62. if ($row !== null && ($existing === null || $existing->target !== $row->target
  63. || $existing->telegram_chat_id !== $row->telegram_chat_id || $existing->bot_token !== $row->bot_token)) {
  64. throw ValidationException::withMessages(['id' => '频道已变更,请刷新后重试']);
  65. }
  66. $match = (clone $channels)->where(function (Builder $query) use ($identity) {
  67. $query->where('target', $identity['target']);
  68. if ($identity['telegram_chat_id'] !== null) {
  69. $query->orWhere('telegram_chat_id', $identity['telegram_chat_id']);
  70. }
  71. })->get();
  72. if ($legacy && $row === null && $match->count() === 1) {
  73. $existing = $match->first();
  74. if ($existing->bot_token !== null && $bot === []) {
  75. throw ValidationException::withMessages(['chatId' => '请使用已保存的频道标识,或通过频道管理按 ID 编辑']);
  76. }
  77. }
  78. if ($match->contains(fn ($channel) => (int) $channel->id !== (int) $existing?->id)) {
  79. throw ValidationException::withMessages(['chatId' => '该频道已存在']);
  80. }
  81. $enabled = (bool) ($fields['enabled'] ?? $existing?->enabled ?? true);
  82. $values = [
  83. 'name' => $fields['name'] ?? $existing?->name ?? $identity['title'],
  84. 'target' => $identity['target'],
  85. 'telegram_chat_id' => $identity['telegram_chat_id'],
  86. 'enabled' => $enabled,
  87. 'message' => $message === null
  88. ? ($existing?->message ?? 'null')
  89. : json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  90. 'updated_at' => now(),
  91. ] + $bot;
  92. if ($existing === null) {
  93. $firstLegacy = $legacy && !$channels->exists();
  94. $id = (int) $channels->insertGetId($values + ['created_at' => now()]);
  95. if ($firstLegacy && $enabled) {
  96. $this->settings()->update(['default_channel_id' => $id]);
  97. }
  98. } else {
  99. $id = (int) $existing->id;
  100. $channels->where('id', $id)->update($values);
  101. if (!$enabled && (int) $default->default_channel_id === $id) {
  102. $this->settings()->update(['default_channel_id' => null]);
  103. }
  104. }
  105. return $this->detail($id);
  106. }, 3);
  107. }
  108. public function setDefault(int $id): array
  109. {
  110. return DB::transaction(function () use ($id) {
  111. $this->settings()->lockForUpdate()->first();
  112. $row = $this->find($id);
  113. if (!$row->enabled) {
  114. throw ValidationException::withMessages(['id' => '请先启用频道']);
  115. }
  116. $this->settings()->update(['default_channel_id' => $id]);
  117. return $this->detail($id);
  118. }, 3);
  119. }
  120. public function delete(int $id): void
  121. {
  122. DB::transaction(function () use ($id) {
  123. $default = $this->settings()->lockForUpdate()->first();
  124. $this->find($id);
  125. if ((int) $default->default_channel_id === $id) {
  126. $this->settings()->update(['default_channel_id' => null]);
  127. }
  128. DB::table('telegram_channels')->where('id', $id)->delete();
  129. }, 3);
  130. }
  131. public function legacyMessage(): ?array
  132. {
  133. $row = $this->defaultChannel();
  134. return $row === null ? null : ['chatId' => ltrim($row->target, '@')] + $this->storedMessage($row);
  135. }
  136. public function roomNoticeTarget(): ?string
  137. {
  138. $row = $this->defaultChannel();
  139. return $row === null ? null : ($row->telegram_chat_id ?? $row->target);
  140. }
  141. public function publish(int $id, bool $pin): array
  142. {
  143. $row = $this->find($id);
  144. $channel = $this->present($row, (int) $row->default_channel_id === $id, true);
  145. if (!$channel['enabled']) {
  146. throw ValidationException::withMessages(['id' => '请先启用频道']);
  147. }
  148. if ($channel['type'] === null) {
  149. throw ValidationException::withMessages(['type' => '请先保存要发布的消息']);
  150. }
  151. $params = ['chat_id' => $channel['telegram_chat_id'] ?? $channel['chatId']];
  152. if ($channel['button'] !== []) {
  153. $params['reply_markup'] = json_encode(['inline_keyboard' => $channel['button']], JSON_THROW_ON_ERROR);
  154. }
  155. try {
  156. $telegram = $this->telegram($this->storedToken($row));
  157. $response = $this->send($telegram, $channel, $params);
  158. } catch (TelegramResponseException $exception) {
  159. if (($exception->getHttpStatusCode() ?? 500) < 500) {
  160. return ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => 'Telegram 拒绝发布,请检查机器人发帖权限、频道和消息内容'];
  161. }
  162. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  163. } catch (\Exception) {
  164. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  165. }
  166. $messageId = $response['message_id'] ?? null;
  167. if ($messageId === null) {
  168. return ['sent' => null, 'pinned' => null, 'message_id' => null, 'error' => '未能确认发布结果,请先检查频道'];
  169. }
  170. $pinned = null;
  171. $error = null;
  172. if ($pin) {
  173. try {
  174. $pinned = $telegram->pinChatMessage(['chat_id' => $params['chat_id'], 'message_id' => $messageId]);
  175. if (!$pinned) {
  176. $error = '消息已发布,置顶未成功';
  177. }
  178. } catch (\Exception) {
  179. $pinned = false;
  180. $error = '消息已发布,请在频道中检查置顶状态';
  181. }
  182. }
  183. return ['sent' => true, 'pinned' => $pinned, 'message_id' => $messageId, 'error' => $error];
  184. }
  185. private function send(Api $telegram, array $channel, array $params): array
  186. {
  187. if ($channel['type'] === 'text') {
  188. return $telegram->post('sendMessage', $params + ['text' => $channel['text']])->getResult() ?: [];
  189. }
  190. $image = $channel['type'] === 'image';
  191. $media = $channel[$channel['type']];
  192. $field = $image ? 'photo' : 'video';
  193. $params['caption'] = $channel['text'];
  194. // Only read files produced by the admin upload endpoints on the configured public disk.
  195. $disk = Storage::disk('public');
  196. $prefix = rtrim($disk->url(''), '/') . '/';
  197. $path = str_starts_with($media, $prefix) ? substr($media, strlen($prefix)) : '';
  198. if (preg_match('~\A(?:images|videos)/[a-f0-9]{32}\.(?:jpg|jpeg|png|webp|mp4|mov|avi|webm)\z~i', $path) && $disk->exists($path)) {
  199. $stream = $disk->readStream($path);
  200. if (!is_resource($stream)) {
  201. throw new RuntimeException('Unable to read uploaded media');
  202. }
  203. try {
  204. $params[$field] = InputFile::create($stream, basename($path));
  205. $response = $image ? $telegram->sendPhoto($params) : $telegram->sendVideo($params);
  206. return ['message_id' => $response->get('message_id')];
  207. } finally {
  208. if (is_resource($stream)) {
  209. fclose($stream);
  210. }
  211. }
  212. }
  213. // Telegram fetches external media directly.
  214. return $telegram->post($image ? 'sendPhoto' : 'sendVideo', $params + [$field => $media])->getResult() ?: [];
  215. }
  216. private function validateBot(?string $username, #[\SensitiveParameter] ?string $token, ?object $row): array
  217. {
  218. if ($token === null) {
  219. if ($username !== null && strcasecmp(ltrim($username, '@'), $row->bot_username ?? '') !== 0) {
  220. throw ValidationException::withMessages(['bot_token' => '绑定或更换机器人时请填写 Bot Token']);
  221. }
  222. return [];
  223. }
  224. try {
  225. $bot = $this->telegram($token)->getMe();
  226. } catch (\Exception) {
  227. throw ValidationException::withMessages(['bot_token' => '无法验证 Bot Token,请检查 Token 或 Telegram 连接']);
  228. }
  229. $actualUsername = $bot->get('username');
  230. if (!$bot->get('is_bot') || !is_string($actualUsername) || $actualUsername === '') {
  231. throw ValidationException::withMessages(['bot_token' => 'Bot Token 未返回有效的机器人账号']);
  232. }
  233. if ($username !== null && strcasecmp(ltrim($username, '@'), $actualUsername) !== 0) {
  234. throw ValidationException::withMessages(['bot_username' => '机器人用户名和 Bot Token 不匹配']);
  235. }
  236. return [
  237. 'bot_username' => $actualUsername,
  238. 'bot_name' => mb_substr((string) $bot->get('first_name'), 0, 255),
  239. 'bot_token' => Crypt::encryptString($token),
  240. ];
  241. }
  242. private function storedToken(?object $row): ?string
  243. {
  244. return $row?->bot_token === null ? null : Crypt::decryptString($row->bot_token);
  245. }
  246. protected function telegram(#[\SensitiveParameter] ?string $token): Api
  247. {
  248. return $token === null ? app(Api::class) : new Api($token);
  249. }
  250. private function resolve(string $target, #[\SensitiveParameter] ?string $token): array
  251. {
  252. try {
  253. $chat = $this->telegram($token)->getChat(['chat_id' => $target]);
  254. } catch (\Exception) {
  255. throw ValidationException::withMessages(['chatId' => '无法读取频道,请检查频道标识及机器人是否已加入']);
  256. }
  257. $id = (string) $chat->get('id');
  258. if ($chat->get('type') !== 'channel' || !preg_match('/^-[1-9]\d{1,19}$/D', $id)) {
  259. throw ValidationException::withMessages(['chatId' => '请输入 Telegram 频道,群组和私聊无法使用']);
  260. }
  261. $username = $chat->get('username');
  262. return [
  263. 'target' => $username ? self::normalizeTarget($username) ?? $id : $id,
  264. 'telegram_chat_id' => $id,
  265. 'title' => mb_substr((string) ($chat->get('title') ?: $target), 0, 255),
  266. ];
  267. }
  268. public static function legacyChannel(mixed $value): ?array
  269. {
  270. if (!is_array($value) || ($target = self::normalizeTarget($value['chatId'] ?? null)) === null) {
  271. return null;
  272. }
  273. $value['type'] ??= !empty($value['video']) ? 'video' : (!empty($value['image']) ? 'image' : 'text');
  274. try {
  275. $message = self::message($value);
  276. } catch (ValidationException) {
  277. return null;
  278. }
  279. return [
  280. 'name' => ltrim($target, '@'),
  281. 'target' => $target,
  282. 'telegram_chat_id' => str_starts_with($target, '-') ? $target : null,
  283. 'enabled' => true,
  284. 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  285. ];
  286. }
  287. private static function normalizeTarget(mixed $value): ?string
  288. {
  289. if (!is_string($value)) {
  290. return null;
  291. }
  292. $value = trim($value);
  293. if (preg_match('/^-[1-9]\d{1,19}$/D', $value)) {
  294. return $value;
  295. }
  296. return preg_match('/^@?[a-z][a-z0-9_]{3,31}$/iD', $value) ? '@' . strtolower(ltrim($value, '@')) : null;
  297. }
  298. private static function message(array $input): array
  299. {
  300. $data = Validator::make($input, [
  301. 'type' => 'required|in:text,image,video',
  302. 'text' => 'nullable|required_if:type,text|string|max:' . (($input['type'] ?? null) === 'text' ? 4096 : 1024),
  303. 'image' => 'nullable|required_if:type,image|string|max:2048|url:http,https',
  304. 'video' => 'nullable|required_if:type,video|string|max:2048|url:http,https',
  305. 'button' => 'sometimes|array|list',
  306. 'button.*' => 'required|array|list',
  307. 'button.*.*' => 'required|array',
  308. 'button.*.*.text' => 'required|string',
  309. 'button.*.*.url' => 'required|string|url:http,https,tg',
  310. ])->validate();
  311. foreach (['image', 'video'] as $field) {
  312. $url = $data[$field] ?? '';
  313. $host = rtrim(strtolower(trim(parse_url($url, PHP_URL_HOST) ?? '', '[]')), '.');
  314. if ($url !== '' && (
  315. parse_url($url, PHP_URL_USER) !== null
  316. || $host === 'localhost'
  317. || str_ends_with($host, '.localhost')
  318. || (filter_var($host, FILTER_VALIDATE_IP) && !filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE))
  319. || str_contains(strtolower(rawurldecode(parse_url($url, PHP_URL_PATH) ?? '')), '/_ignition/')
  320. )) {
  321. throw ValidationException::withMessages([$field => '媒体地址须可公开访问']);
  322. }
  323. }
  324. return [
  325. 'type' => $data['type'],
  326. 'text' => $data['text'] ?? '',
  327. 'image' => $data['image'] ?? '',
  328. 'video' => $data['video'] ?? '',
  329. 'button' => array_map(fn ($row) => array_map(
  330. fn ($button) => ['text' => $button['text'], 'url' => $button['url']],
  331. $row,
  332. ), $data['button'] ?? []),
  333. ];
  334. }
  335. private function settings(): Builder
  336. {
  337. return DB::table('telegram_channel_settings')->where('id', 1);
  338. }
  339. private function defaultChannel(): ?object
  340. {
  341. return $this->joinedChannels()->where('channels.enabled', true)
  342. ->whereColumn('channels.id', 'settings.default_channel_id')->first();
  343. }
  344. private function find(int $id): object
  345. {
  346. return $this->joinedChannels()->where('channels.id', $id)->first()
  347. ?? throw ValidationException::withMessages(['id' => '频道不存在']);
  348. }
  349. private function joinedChannels(): Builder
  350. {
  351. return DB::table('telegram_channels as channels')
  352. ->crossJoin('telegram_channel_settings as settings')
  353. ->select('channels.*', 'settings.default_channel_id')
  354. ->where('settings.id', 1);
  355. }
  356. private function present(object $row, bool $default, bool $withMessage = false): array
  357. {
  358. $data = [
  359. 'id' => (int) $row->id,
  360. 'name' => $row->name,
  361. 'chatId' => $row->target,
  362. 'telegram_chat_id' => $row->telegram_chat_id,
  363. 'bot_username' => $row->bot_username,
  364. 'bot_name' => $row->bot_name,
  365. 'has_bot_token' => $row->bot_token !== null,
  366. 'enabled' => (bool) $row->enabled,
  367. 'is_default' => $default,
  368. ];
  369. return $withMessage ? $data + $this->storedMessage($row) : $data;
  370. }
  371. private function storedMessage(object $row): array
  372. {
  373. return json_decode($row->message, true) ?? [
  374. 'type' => null,
  375. 'text' => '',
  376. 'image' => '',
  377. 'video' => '',
  378. 'button' => [],
  379. ];
  380. }
  381. }