TelegramChannelTest.php 16 KB

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