TelegramChannelTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Http\Controllers\admin\Config;
  4. use App\Http\Controllers\admin\TelegramChannel;
  5. use App\Http\Middleware\CheckButtonPermission;
  6. use App\Services\ChannelService;
  7. use App\Services\TelegramChannelService;
  8. use GuzzleHttp\Client;
  9. use GuzzleHttp\Handler\MockHandler;
  10. use GuzzleHttp\HandlerStack;
  11. use GuzzleHttp\Middleware;
  12. use GuzzleHttp\Psr7\Response;
  13. use Illuminate\Config\Repository;
  14. use Illuminate\Contracts\Routing\ResponseFactory;
  15. use Illuminate\Database\Capsule\Manager;
  16. use Illuminate\Database\Schema\Blueprint;
  17. use Illuminate\Encryption\Encrypter;
  18. use Illuminate\Filesystem\FilesystemServiceProvider;
  19. use Illuminate\Foundation\Application;
  20. use Illuminate\Http\Request;
  21. use Illuminate\Routing\Route;
  22. use Illuminate\Support\Facades\Crypt;
  23. use Illuminate\Support\Facades\DB;
  24. use Illuminate\Support\Facades\Facade;
  25. use Illuminate\Support\Facades\Schema;
  26. use Illuminate\Support\Facades\Storage;
  27. use Illuminate\Translation\ArrayLoader;
  28. use Illuminate\Translation\Translator;
  29. use Illuminate\Validation\Factory;
  30. use PHPUnit\Framework\TestCase;
  31. use Telegram\Bot\Api;
  32. use Telegram\Bot\HttpClients\GuzzleHttpClient;
  33. use Tests\Support\JsonResponseFactory;
  34. class TelegramChannelTest extends TestCase
  35. {
  36. private Application $app;
  37. private TelegramChannelService $service;
  38. private MockHandler $telegram;
  39. private array $requests = [];
  40. protected function setUp(): void
  41. {
  42. Facade::clearResolvedInstances();
  43. $this->app = new Application(dirname(__DIR__, 2));
  44. $this->app->instance('config', new Repository([
  45. 'app' => ['locale' => 'zh'],
  46. 'filesystems' => ['disks' => ['public' => [
  47. 'driver' => 'local', 'root' => sys_get_temp_dir(), 'url' => 'https://admin.example.com/storage',
  48. ]]],
  49. ]));
  50. Facade::setFacadeApplication($this->app);
  51. $db = new Manager($this->app);
  52. $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => 'bot_']);
  53. $db->setAsGlobal();
  54. $db->bootEloquent();
  55. $this->app->instance('db', $db->getDatabaseManager());
  56. $this->app->bind('db.schema', fn () => $db->schema());
  57. $translator = new Translator(new ArrayLoader(), 'zh');
  58. $this->app->instance('translator', $translator);
  59. $this->app->instance('validator', new Factory($translator, $this->app));
  60. $this->app->instance(ResponseFactory::class, new JsonResponseFactory());
  61. Request::macro('validate', function (array $rules) {
  62. return app('validator')->make($this->all(), $rules)->validate();
  63. });
  64. Schema::create('config', function (Blueprint $table) {
  65. $table->id();
  66. $table->string('field')->unique();
  67. $table->text('val');
  68. $table->integer('group_id')->default(2);
  69. });
  70. $this->telegram = new MockHandler();
  71. $stack = HandlerStack::create($this->telegram);
  72. $stack->push(Middleware::history($this->requests));
  73. $client = new GuzzleHttpClient(new Client(['handler' => $stack]));
  74. $this->app->instance(Api::class, new Api('1:fixture', false, $client));
  75. $this->app->instance('encrypter', new Encrypter(random_bytes(32), 'aes-256-cbc'));
  76. $this->service = new class($client) extends TelegramChannelService {
  77. public function __construct(private GuzzleHttpClient $client) {}
  78. protected function telegram(#[\SensitiveParameter] ?string $token): Api
  79. {
  80. return $token === null ? parent::telegram(null) : new Api($token, false, $this->client);
  81. }
  82. };
  83. }
  84. protected function tearDown(): void
  85. {
  86. DB::disconnect();
  87. Facade::clearResolvedInstances();
  88. parent::tearDown();
  89. }
  90. private function migrate(?array $legacy = null): void
  91. {
  92. if ($legacy !== null) {
  93. DB::table('config')->insert(['field' => 'channel_message', 'val' => json_encode($legacy)]);
  94. }
  95. (require database_path('migrations/2026_11_13_150000_create_telegram_channels.php'))->up();
  96. (require database_path('migrations/2026_11_13_150200_add_bot_credentials_to_telegram_channels.php'))->up();
  97. }
  98. private function request(array $data = [], string $method = 'POST', int $userId = 1): Request
  99. {
  100. $request = TelegramChannelTestRequest::create('/admin/telegramChannel', $method, $data);
  101. $request->user = (object) ['id' => $userId];
  102. $this->app->instance('request', $request);
  103. return $request;
  104. }
  105. private function telegramResult(mixed $result): void
  106. {
  107. $this->telegram->append(new Response(200, [], json_encode(['ok' => true, 'result' => $result])));
  108. }
  109. private function telegramChannel(int $id, ?string $username = null): void
  110. {
  111. $this->telegramResult(['id' => $id, 'type' => 'channel', 'username' => $username, 'title' => '频道']);
  112. }
  113. private function message(string $chatId, string $text): array
  114. {
  115. return [
  116. 'chatId' => $chatId, 'type' => 'text', 'text' => $text,
  117. 'button' => [[['text' => '网站', 'url' => 'https://example.com']]],
  118. ];
  119. }
  120. public function test_migrates_old_image_message_and_does_not_overwrite_it_when_saving_another_channel(): void
  121. {
  122. $legacy = [
  123. 'chatId' => 'OriginalChannel', 'image' => 'https://example.com/menu.jpg', 'text' => '旧文案',
  124. 'button' => [[['text' => '网站', 'url' => 'https://example.com']]],
  125. ];
  126. $this->migrate($legacy);
  127. $this->assertSame([], $this->requests);
  128. $default = $this->service->list()[0];
  129. $this->assertTrue($default['is_default']);
  130. $this->telegramChannel(-1001234567890);
  131. $this->request($this->message('-1001234567890', '第二个频道') + ['isSend' => false]);
  132. $this->assertSame(0, (new Config())->sendChannelMessage($this->service)->getData(true)['code']);
  133. $this->assertCount(1, $this->requests);
  134. $this->assertCount(2, $this->service->list());
  135. $this->request(['field' => 'channel_message'], 'GET');
  136. $controller = new Config();
  137. $value = $controller->get()->getData(true)['data']['channel_message'];
  138. $this->assertSame('originalchannel', $value['chatId']);
  139. $this->assertSame('image', $value['type']);
  140. $this->assertSame($legacy['button'], $value['button']);
  141. $this->assertSame($value, $controller->getAll()->getData(true)['data']['channel_message']);
  142. $this->assertSame(json_encode($legacy), DB::table('config')->value('val'));
  143. }
  144. public function test_quarantines_local_debug_url_and_denies_generic_write_without_channel_permission(): void
  145. {
  146. $legacy = [
  147. 'chatId' => 'test', 'type' => 'image', 'text' => 'test',
  148. 'image' => 'http://127.0.0.1/_ignition/execute-solution', 'video' => '',
  149. ];
  150. $this->migrate($legacy);
  151. $this->assertSame([], $this->service->list());
  152. $this->assertNull(ChannelService::createRoomNotice('missing'));
  153. $this->request(['field' => 'channel_message', 'val' => json_encode($legacy)]);
  154. $this->assertNotSame(0, (new Config())->setField()->getData(true)['code']);
  155. $this->installPermissions();
  156. $this->request(['field' => 'channel_message', 'val' => $this->message('@another', '禁止')], userId: 2);
  157. $this->assertSame(101009, (new Config())->setField()->getData(true)['code']);
  158. $this->assertSame(json_encode($legacy), DB::table('config')->value('val'));
  159. $this->assertSame([], $this->requests);
  160. }
  161. public function test_edits_one_channel_and_routes_room_notices_only_to_the_enabled_default(): void
  162. {
  163. $this->migrate();
  164. Schema::create('rooms', function (Blueprint $table) {
  165. $table->string('room_id');
  166. $table->string('game_name');
  167. $table->integer('rounds');
  168. $table->integer('base_score');
  169. $table->integer('participants');
  170. });
  171. DB::table('rooms')->insert(['room_id' => '123', 'game_name' => '游戏', 'rounds' => 3, 'base_score' => 10, 'participants' => 4]);
  172. $this->telegramChannel(-1001000000001, 'first_channel');
  173. $first = $this->service->save($this->message('@first_channel', '一'));
  174. $this->telegramChannel(-1001000000002, 'second_channel');
  175. $second = $this->service->save(['chatId' => '@second_channel']);
  176. $this->assertNull($second['type']);
  177. $request = $this->request(['id' => $second['id']]);
  178. $this->assertSame(-3, (new TelegramChannel())->publish($request, $this->service)->getData(true)['code']);
  179. $this->service->setDefault($second['id']);
  180. $this->assertSame('-1001000000002', ChannelService::createRoomNotice('123')['chat_id']);
  181. $this->service->save($this->message('@second_channel', '二') + ['id' => $second['id'], 'enabled' => false]);
  182. $this->assertSame('一', $this->service->detail($first['id'])['text']);
  183. $this->assertSame('二', $this->service->detail($second['id'])['text']);
  184. $this->assertNull(ChannelService::createRoomNotice('123'));
  185. $this->service->setDefault($first['id']);
  186. $this->service->delete($first['id']);
  187. $this->assertNull(ChannelService::createRoomNotice('123'));
  188. $this->assertCount(2, $this->requests);
  189. }
  190. public function test_publishes_only_to_selected_channel_and_reports_pin_failure_separately(): void
  191. {
  192. $this->migrate();
  193. $this->telegramChannel(-1001000000001, 'first_channel');
  194. $first = $this->service->save($this->message('@first_channel', '一'));
  195. $this->service->setDefault($first['id']);
  196. $this->telegramChannel(-1001000000002);
  197. $second = $this->service->save($this->message('-1001000000002', '二'));
  198. $this->telegramResult(['message_id' => 37]);
  199. $this->telegram->append(new Response(400, [], '{"ok":false,"error_code":400,"description":"pin rejected"}'));
  200. $request = $this->request(['id' => $second['id'], 'isTop' => true]);
  201. $result = (new TelegramChannel())->publish($request, $this->service)->getData(true);
  202. $this->assertSame(0, $result['code']);
  203. $this->assertSame(['sent' => true, 'pinned' => false, 'message_id' => 37], array_intersect_key($result['data'], array_flip(['sent', 'pinned', 'message_id'])));
  204. $this->assertCount(4, $this->requests);
  205. parse_str((string) $this->requests[2]['request']->getBody(), $sent);
  206. $this->assertSame('-1001000000002', $sent['chat_id']);
  207. $this->assertSame('二', $sent['text']);
  208. $this->assertSame($second['button'], json_decode($sent['reply_markup'], true)['inline_keyboard']);
  209. parse_str((string) $this->requests[3]['request']->getBody(), $pin);
  210. $this->assertSame(['chat_id' => '-1001000000002', 'message_id' => '37'], $pin);
  211. }
  212. private function installPermissions(): void
  213. {
  214. Schema::create('menus', function (Blueprint $table) {
  215. $table->id();
  216. $table->unsignedBigInteger('parent_id')->default(0);
  217. $table->string('title')->default('');
  218. $table->string('uri');
  219. $table->string('permission_name')->nullable();
  220. $table->integer('type');
  221. $table->integer('sort')->default(0);
  222. $table->integer('status')->default(1);
  223. $table->timestamps();
  224. });
  225. Schema::create('role_menu', function (Blueprint $table) {
  226. $table->unsignedBigInteger('menu_id');
  227. $table->unsignedBigInteger('role_id');
  228. $table->primary(['menu_id', 'role_id']);
  229. });
  230. Schema::create('roles', function (Blueprint $table) {
  231. $table->id();
  232. });
  233. Schema::create('role_user', function (Blueprint $table) {
  234. $table->unsignedBigInteger('user_id');
  235. $table->unsignedBigInteger('role_id');
  236. });
  237. $previous = DB::table('menus')->insertGetId(['uri' => 'admin/config/sendChannelMessage', 'type' => 2]);
  238. DB::table('role_menu')->insert(['menu_id' => $previous, 'role_id' => 8]);
  239. (require database_path('migrations/2026_11_13_150100_add_telegram_channel_permissions.php'))->up();
  240. }
  241. public function test_old_permission_is_carried_forward_and_channel_ids_are_deduplicated(): void
  242. {
  243. $this->migrate();
  244. $this->installPermissions();
  245. $role = DB::table('role_menu')->join('menus', 'menus.id', '=', 'role_menu.menu_id')->where('role_id', 8);
  246. $this->assertContains(TelegramChannelService::MANAGE, $role->pluck('uri')->all());
  247. $this->assertContains(TelegramChannelService::PUBLISH, $role->pluck('uri')->all());
  248. DB::table('role_user')->insert(['user_id' => 2, 'role_id' => 8]);
  249. $this->telegramChannel(-1001000000001, 'first_channel');
  250. $this->request(['field' => 'channel_message', 'val' => $this->message('@first_channel', '允许')], userId: 2);
  251. $this->assertSame(0, (new Config())->setField()->getData(true)['code']);
  252. $this->telegramChannel(-1001000000001, 'first_channel');
  253. $request = $this->request(['chatId' => '-1001000000001']);
  254. $this->assertSame(-3, (new TelegramChannel())->save($request, $this->service)->getData(true)['code']);
  255. $this->assertCount(1, $this->service->list());
  256. }
  257. public function test_channel_tokens_are_encrypted_and_the_correct_bot_publishes_each_channel(): void
  258. {
  259. $this->migrate();
  260. $firstToken = '111:fixture_first';
  261. $secondToken = '222:fixture_second';
  262. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'first_bot', 'first_name' => '机器人一']);
  263. $this->telegramChannel(-1001000000001, 'first_channel');
  264. $request = $this->request($this->message('@first_channel', '一') + [
  265. 'bot_username' => '@FIRST_BOT', 'bot_token' => $firstToken,
  266. ]);
  267. $saved = (new TelegramChannel())->save($request, $this->service)->getData(true);
  268. $this->assertSame(0, $saved['code']);
  269. $first = $saved['data'];
  270. $this->assertSame('first_bot', $first['bot_username']);
  271. $this->assertSame('机器人一', $first['bot_name']);
  272. $this->assertTrue($first['has_bot_token']);
  273. $this->assertArrayNotHasKey('bot_token', $first);
  274. $encrypted = DB::table('telegram_channels')->where('id', $first['id'])->value('bot_token');
  275. $this->assertNotSame($firstToken, $encrypted);
  276. $this->assertSame($firstToken, Crypt::decryptString($encrypted));
  277. $this->telegramResult(['id' => 222, 'is_bot' => true, 'username' => 'second_bot', 'first_name' => '机器人二']);
  278. $this->telegramChannel(-1001000000002, 'second_channel');
  279. $second = $this->service->save($this->message('@second_channel', '二') + ['bot_token' => $secondToken]);
  280. $this->service->save(['id' => $first['id'], 'chatId' => $first['chatId'], 'name' => '改名', 'bot_token' => null]);
  281. $this->assertSame($encrypted, DB::table('telegram_channels')->where('id', $first['id'])->value('bot_token'));
  282. $this->telegramResult(['message_id' => 10]);
  283. $this->telegramResult(true);
  284. $this->telegramResult(['message_id' => 20]);
  285. $this->assertTrue($this->service->publish($first['id'], true)['pinned']);
  286. $this->assertTrue($this->service->publish($second['id'], false)['sent']);
  287. $paths = array_map(fn ($entry) => $entry['request']->getUri()->getPath(), $this->requests);
  288. $this->assertSame([
  289. "/bot$firstToken/getMe", "/bot$firstToken/getChat", "/bot$secondToken/getMe", "/bot$secondToken/getChat",
  290. "/bot$firstToken/sendMessage", "/bot$firstToken/pinChatMessage", "/bot$secondToken/sendMessage",
  291. ], $paths);
  292. $this->assertSame('1:fixture', $this->app->make(Api::class)->getAccessToken());
  293. $this->assertArrayNotHasKey('bot_token', $this->service->list()[0]);
  294. }
  295. public function test_wrong_bot_username_does_not_replace_existing_token(): void
  296. {
  297. $this->migrate();
  298. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'first_bot', 'first_name' => '机器人一']);
  299. $this->telegramChannel(-1001000000001, 'first_channel');
  300. $first = $this->service->save($this->message('@first_channel', '一') + ['bot_token' => '111:fixture_first']);
  301. $before = DB::table('telegram_channels')->where('id', $first['id'])->value('bot_token');
  302. $this->telegramResult(['id' => 222, 'is_bot' => true, 'username' => 'second_bot', 'first_name' => '机器人二']);
  303. $request = $this->request([
  304. 'id' => $first['id'], 'chatId' => $first['chatId'],
  305. 'bot_username' => 'first_bot', 'bot_token' => '222:fixture_second',
  306. ]);
  307. $result = (new TelegramChannel())->save($request, $this->service)->getData(true);
  308. $this->assertSame(-3, $result['code']);
  309. $this->assertStringContainsString('不匹配', $result['msg']);
  310. $this->assertStringNotContainsString('222:fixture_second', $result['msg']);
  311. $this->assertSame($before, DB::table('telegram_channels')->where('id', $first['id'])->value('bot_token'));
  312. }
  313. public function test_publish_permission_is_independent_from_save_permission(): void
  314. {
  315. $this->migrate();
  316. $this->installPermissions();
  317. DB::table('roles')->insert(['id' => 9]);
  318. DB::table('role_user')->insert(['user_id' => 2, 'role_id' => 9]);
  319. $saveButton = DB::table('menus')->where('uri', TelegramChannelService::MANAGE)->value('id');
  320. DB::table('role_menu')->insert(['menu_id' => $saveButton, 'role_id' => 9]);
  321. $request = $this->request(userId: 2);
  322. $middleware = new CheckButtonPermission();
  323. $save = (new Route('POST', TelegramChannelService::MANAGE, fn () => null))->defaults('require_active_button', true);
  324. $request->setRouteResolver(fn () => $save);
  325. $this->assertTrue($middleware->handle($request, fn () => true));
  326. $publish = (new Route('POST', TelegramChannelService::PUBLISH, fn () => null))->defaults('require_active_button', true);
  327. $request->setRouteResolver(fn () => $publish);
  328. $this->assertSame(-1, $middleware->handle($request, fn () => true)->getData(true)['code']);
  329. $this->assertSame([], $this->requests);
  330. }
  331. public function test_external_media_url_is_passed_to_telegram_without_downloading_it(): void
  332. {
  333. $this->migrate();
  334. $this->app->register(FilesystemServiceProvider::class);
  335. $this->telegramChannel(-1001000000001, 'first_channel');
  336. $media = 'https://files.example.test/photo.jpg';
  337. $channel = $this->service->save(['chatId' => '@first_channel', 'type' => 'image', 'image' => $media]);
  338. $this->telegramResult(['message_id' => 18]);
  339. $this->assertTrue($this->service->publish($channel['id'], false)['sent']);
  340. $this->assertStringEndsWith('/sendPhoto', $this->requests[1]['request']->getUri()->getPath());
  341. parse_str((string) $this->requests[1]['request']->getBody(), $sent);
  342. $this->assertSame($media, $sent['photo']);
  343. }
  344. public function test_admin_upload_is_sent_as_a_file_and_migration_can_be_retried(): void
  345. {
  346. $this->migrate();
  347. $this->app->register(FilesystemServiceProvider::class);
  348. $disk = Storage::disk('public');
  349. $file = 'videos/' . bin2hex(random_bytes(16)) . '.mp4';
  350. $disk->put($file, 'test video');
  351. try {
  352. $this->telegramChannel(-1001000000001, 'first_channel');
  353. $channel = $this->service->save([
  354. 'chatId' => '@first_channel', 'type' => 'video', 'video' => $disk->url($file),
  355. ]);
  356. $this->service->setDefault($channel['id']);
  357. (require database_path('migrations/2026_11_13_150000_create_telegram_channels.php'))->up();
  358. $this->assertTrue($this->service->detail($channel['id'])['is_default']);
  359. $this->telegram->append(function ($request) {
  360. $this->assertStringEndsWith('/sendVideo', $request->getUri()->getPath());
  361. $this->assertStringStartsWith('multipart/form-data;', $request->getHeaderLine('Content-Type'));
  362. $this->assertStringContainsString('test video', (string) $request->getBody());
  363. return new Response(200, [], '{"ok":true,"result":{"message_id":18}}');
  364. });
  365. $this->assertTrue($this->service->publish($channel['id'], false)['sent']);
  366. } finally {
  367. $disk->delete($file);
  368. }
  369. }
  370. }
  371. class TelegramChannelTestRequest extends Request
  372. {
  373. public object $user;
  374. }