TelegramChannelService.php 18 KB

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