TelegramChannelTest.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. (require database_path('migrations/2026_11_13_150300_create_telegram_bots.php'))->up();
  98. }
  99. private function request(array $data = [], string $method = 'POST', int $userId = 1): Request
  100. {
  101. $request = TelegramChannelTestRequest::create('/admin/telegramChannel', $method, $data);
  102. $request->user = (object) ['id' => $userId];
  103. $this->app->instance('request', $request);
  104. return $request;
  105. }
  106. private function telegramResult(mixed $result): void
  107. {
  108. $this->telegram->append(new Response(200, [], json_encode(['ok' => true, 'result' => $result])));
  109. }
  110. private function telegramChannel(int $id, ?string $username = null): void
  111. {
  112. $this->telegramResult(['id' => $id, 'type' => 'channel', 'username' => $username, 'title' => '频道']);
  113. }
  114. private function message(string $chatId, string $text): array
  115. {
  116. return [
  117. 'chatId' => $chatId, 'type' => 'text', 'text' => $text,
  118. 'button' => [[['text' => '网站', 'url' => 'https://example.com']]],
  119. ];
  120. }
  121. public function test_migrates_old_image_message_and_does_not_overwrite_it_when_saving_another_channel(): void
  122. {
  123. $legacy = [
  124. 'chatId' => 'OriginalChannel', 'image' => 'https://example.com/menu.jpg', 'text' => '旧文案',
  125. 'button' => [[['text' => '网站', 'url' => 'https://example.com']]],
  126. ];
  127. $this->migrate($legacy);
  128. $this->assertSame([], $this->requests);
  129. $default = $this->service->list()[0];
  130. $this->assertTrue($default['is_default']);
  131. $this->telegramChannel(-1001234567890);
  132. $this->request($this->message('-1001234567890', '第二个频道') + ['isSend' => false]);
  133. $this->assertSame(0, (new Config())->sendChannelMessage($this->service)->getData(true)['code']);
  134. $this->assertCount(1, $this->requests);
  135. $this->assertCount(2, $this->service->list());
  136. $this->request(['field' => 'channel_message'], 'GET');
  137. $controller = new Config();
  138. $value = $controller->get()->getData(true)['data']['channel_message'];
  139. $this->assertSame('originalchannel', $value['chatId']);
  140. $this->assertSame('image', $value['type']);
  141. $this->assertSame($legacy['button'], $value['button']);
  142. $this->assertSame($value, $controller->getAll()->getData(true)['data']['channel_message']);
  143. $this->assertSame(json_encode($legacy), DB::table('config')->value('val'));
  144. }
  145. public function test_quarantines_local_debug_url_and_denies_generic_write_without_channel_permission(): void
  146. {
  147. $legacy = [
  148. 'chatId' => 'test', 'type' => 'image', 'text' => 'test',
  149. 'image' => 'http://127.0.0.1/_ignition/execute-solution', 'video' => '',
  150. ];
  151. $this->migrate($legacy);
  152. $this->assertSame([], $this->service->list());
  153. $this->assertNull(ChannelService::createRoomNotice('missing'));
  154. $this->request(['field' => 'channel_message', 'val' => json_encode($legacy)]);
  155. $this->assertNotSame(0, (new Config())->setField()->getData(true)['code']);
  156. $this->installPermissions();
  157. $this->request(['field' => 'channel_message', 'val' => $this->message('@another', '禁止')], userId: 2);
  158. $this->assertSame(101009, (new Config())->setField()->getData(true)['code']);
  159. $this->assertSame(json_encode($legacy), DB::table('config')->value('val'));
  160. $this->assertSame([], $this->requests);
  161. }
  162. public function test_edits_one_channel_and_routes_room_notices_only_to_the_enabled_default(): void
  163. {
  164. $this->migrate();
  165. Schema::create('rooms', function (Blueprint $table) {
  166. $table->string('room_id');
  167. $table->string('game_name');
  168. $table->integer('rounds');
  169. $table->integer('base_score');
  170. $table->integer('participants');
  171. });
  172. DB::table('rooms')->insert(['room_id' => '123', 'game_name' => '游戏', 'rounds' => 3, 'base_score' => 10, 'participants' => 4]);
  173. $this->telegramChannel(-1001000000001, 'first_channel');
  174. $first = $this->service->save($this->message('@first_channel', '一'));
  175. $this->telegramChannel(-1001000000002, 'second_channel');
  176. $second = $this->service->save(['chatId' => '@second_channel']);
  177. $this->assertNull($second['type']);
  178. $request = $this->request(['id' => $second['id']]);
  179. $this->assertSame(-3, (new TelegramChannel())->publish($request, $this->service)->getData(true)['code']);
  180. $this->service->setDefault($second['id']);
  181. $this->assertSame('-1001000000002', ChannelService::createRoomNotice('123')['chat_id']);
  182. $this->service->save($this->message('@second_channel', '二') + ['id' => $second['id'], 'enabled' => false]);
  183. $this->assertSame('一', $this->service->detail($first['id'])['text']);
  184. $this->assertSame('二', $this->service->detail($second['id'])['text']);
  185. $this->assertNull(ChannelService::createRoomNotice('123'));
  186. $this->service->setDefault($first['id']);
  187. $this->service->delete($first['id']);
  188. $this->assertNull(ChannelService::createRoomNotice('123'));
  189. $this->assertCount(2, $this->requests);
  190. }
  191. public function test_publishes_only_to_selected_channel_and_reports_pin_failure_separately(): void
  192. {
  193. $this->migrate();
  194. $this->telegramChannel(-1001000000001, 'first_channel');
  195. $first = $this->service->save($this->message('@first_channel', '一'));
  196. $this->service->setDefault($first['id']);
  197. $this->telegramChannel(-1001000000002);
  198. $second = $this->service->save($this->message('-1001000000002', '二'));
  199. $this->telegramResult(['message_id' => 37]);
  200. $this->telegram->append(new Response(400, [], '{"ok":false,"error_code":400,"description":"pin rejected"}'));
  201. $request = $this->request(['id' => $second['id'], 'isTop' => true]);
  202. $result = (new TelegramChannel())->publish($request, $this->service)->getData(true);
  203. $this->assertSame(0, $result['code']);
  204. $this->assertSame(['sent' => true, 'pinned' => false, 'message_id' => 37], array_intersect_key($result['data'], array_flip(['sent', 'pinned', 'message_id'])));
  205. $this->assertCount(4, $this->requests);
  206. parse_str((string) $this->requests[2]['request']->getBody(), $sent);
  207. $this->assertSame('-1001000000002', $sent['chat_id']);
  208. $this->assertSame('二', $sent['text']);
  209. $this->assertSame($second['button'], json_decode($sent['reply_markup'], true)['inline_keyboard']);
  210. parse_str((string) $this->requests[3]['request']->getBody(), $pin);
  211. $this->assertSame(['chat_id' => '-1001000000002', 'message_id' => '37'], $pin);
  212. }
  213. private function installPermissions(): void
  214. {
  215. Schema::create('menus', function (Blueprint $table) {
  216. $table->id();
  217. $table->unsignedBigInteger('parent_id')->default(0);
  218. $table->string('title')->default('');
  219. $table->string('uri');
  220. $table->string('permission_name')->nullable();
  221. $table->integer('type');
  222. $table->integer('sort')->default(0);
  223. $table->integer('status')->default(1);
  224. $table->timestamps();
  225. });
  226. Schema::create('role_menu', function (Blueprint $table) {
  227. $table->unsignedBigInteger('menu_id');
  228. $table->unsignedBigInteger('role_id');
  229. $table->primary(['menu_id', 'role_id']);
  230. });
  231. Schema::create('roles', function (Blueprint $table) {
  232. $table->id();
  233. });
  234. Schema::create('role_user', function (Blueprint $table) {
  235. $table->unsignedBigInteger('user_id');
  236. $table->unsignedBigInteger('role_id');
  237. });
  238. $previous = DB::table('menus')->insertGetId(['uri' => 'admin/config/sendChannelMessage', 'type' => 2]);
  239. DB::table('role_menu')->insert(['menu_id' => $previous, 'role_id' => 8]);
  240. (require database_path('migrations/2026_11_13_150100_add_telegram_channel_permissions.php'))->up();
  241. }
  242. public function test_old_permission_is_carried_forward_and_channel_ids_are_deduplicated(): void
  243. {
  244. $this->migrate();
  245. $this->installPermissions();
  246. $role = DB::table('role_menu')->join('menus', 'menus.id', '=', 'role_menu.menu_id')->where('role_id', 8);
  247. $this->assertContains(TelegramChannelService::MANAGE, $role->pluck('uri')->all());
  248. $this->assertContains(TelegramChannelService::PUBLISH, $role->pluck('uri')->all());
  249. DB::table('role_user')->insert(['user_id' => 2, 'role_id' => 8]);
  250. $this->telegramChannel(-1001000000001, 'first_channel');
  251. $this->request(['field' => 'channel_message', 'val' => $this->message('@first_channel', '允许')], userId: 2);
  252. $this->assertSame(0, (new Config())->setField()->getData(true)['code']);
  253. $this->telegramChannel(-1001000000001, 'first_channel');
  254. $request = $this->request(['chatId' => '-1001000000001']);
  255. $this->assertSame(-3, (new TelegramChannel())->save($request, $this->service)->getData(true)['code']);
  256. $this->assertCount(1, $this->service->list());
  257. }
  258. public function test_blank_channel_name_defaults_on_create_and_is_preserved_on_edit(): void
  259. {
  260. $this->migrate();
  261. $this->telegramChannel(-1001000000001, 'first_channel');
  262. $request = $this->request(['chatId' => '@first_channel', 'name' => ' ']);
  263. $controller = new TelegramChannel();
  264. $saved = $controller->save($request, $this->service)->getData(true);
  265. $this->assertSame(0, $saved['code']);
  266. $this->assertSame('频道', $saved['data']['name']);
  267. $edit = ['id' => $saved['data']['id'], 'chatId' => '@first_channel'];
  268. $request = $this->request($edit + ['name' => ' 后台自定义名称 ']);
  269. $this->assertSame('后台自定义名称', $controller->save($request, $this->service)->getData(true)['data']['name']);
  270. $request = $this->request($edit + ['name' => null]);
  271. $this->assertSame('后台自定义名称', $controller->save($request, $this->service)->getData(true)['data']['name']);
  272. $this->assertCount(1, $this->requests);
  273. }
  274. public function test_channel_tokens_are_encrypted_and_the_correct_bot_publishes_each_channel(): void
  275. {
  276. $this->migrate();
  277. $firstToken = '111:fixture_first';
  278. $secondToken = '222:fixture_second';
  279. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'first_bot', 'first_name' => '机器人一']);
  280. $this->telegramChannel(-1001000000001, 'first_channel');
  281. $request = $this->request($this->message('@first_channel', '一') + [
  282. 'bot_username' => '@FIRST_BOT', 'bot_token' => $firstToken,
  283. ]);
  284. $saved = (new TelegramChannel())->save($request, $this->service)->getData(true);
  285. $this->assertSame(0, $saved['code']);
  286. $first = $saved['data'];
  287. $this->assertSame('first_bot', $first['bot_username']);
  288. $this->assertSame('机器人一', $first['bot_name']);
  289. $this->assertTrue($first['has_bot_token']);
  290. $this->assertArrayNotHasKey('bot_token', $first);
  291. $encrypted = DB::table('telegram_bots')->where('id', $first['bot_id'])->value('bot_token');
  292. $this->assertNotSame($firstToken, $encrypted);
  293. $this->assertSame($firstToken, Crypt::decryptString($encrypted));
  294. $this->telegramResult(['id' => 222, 'is_bot' => true, 'username' => 'second_bot', 'first_name' => '机器人二']);
  295. $this->telegramChannel(-1001000000002, 'second_channel');
  296. $second = $this->service->save($this->message('@second_channel', '二') + ['bot_token' => $secondToken]);
  297. $this->service->save(['id' => $first['id'], 'chatId' => $first['chatId'], 'name' => '改名', 'bot_token' => null]);
  298. $this->assertSame($encrypted, DB::table('telegram_bots')->where('id', $first['bot_id'])->value('bot_token'));
  299. $this->telegramResult(['message_id' => 10]);
  300. $this->telegramResult(true);
  301. $this->telegramResult(['message_id' => 20]);
  302. $this->assertTrue($this->service->publish($first['id'], true)['pinned']);
  303. $this->assertTrue($this->service->publish($second['id'], false)['sent']);
  304. $paths = array_map(fn ($entry) => $entry['request']->getUri()->getPath(), $this->requests);
  305. $this->assertSame([
  306. "/bot$firstToken/getMe", "/bot$firstToken/getChat", "/bot$secondToken/getMe", "/bot$secondToken/getChat",
  307. "/bot$firstToken/sendMessage", "/bot$firstToken/pinChatMessage", "/bot$secondToken/sendMessage",
  308. ], $paths);
  309. $this->assertSame('1:fixture', $this->app->make(Api::class)->getAccessToken());
  310. $this->assertArrayNotHasKey('bot_token', $this->service->list()[0]);
  311. }
  312. public function test_registered_bot_can_be_reused_rotated_and_deleted_after_unbinding(): void
  313. {
  314. $this->migrate();
  315. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'shared_bot', 'first_name' => '机器人']);
  316. $bot = $this->service->saveBot(['bot_token' => '111:fixture_initial']);
  317. $this->assertArrayNotHasKey('bot_token', $bot);
  318. $this->assertSame($bot['id'], (int) $this->service->bots()[0]->id);
  319. $this->telegramChannel(-1001000000001, 'first_channel');
  320. $first = $this->service->save($this->message('@first_channel', '一') + ['bot_id' => $bot['id']]);
  321. $this->telegramChannel(-1001000000002, 'second_channel');
  322. $second = $this->service->save($this->message('@second_channel', '二') + ['bot_id' => $bot['id']]);
  323. $this->assertSame($first['bot_id'], $second['bot_id']);
  324. $request = $this->request(['id' => $bot['id']]);
  325. $this->assertSame(-3, (new TelegramChannel())->deleteBot($request, $this->service)->getData(true)['code']);
  326. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'shared_bot', 'first_name' => '机器人']);
  327. $this->service->saveBot(['id' => $bot['id'], 'bot_token' => '111:fixture_rotated']);
  328. $this->telegramResult(['message_id' => 10]);
  329. $this->assertTrue($this->service->publish($first['id'], false)['sent']);
  330. $this->assertSame('/bot111:fixture_rotated/sendMessage', $this->requests[4]['request']->getUri()->getPath());
  331. $this->telegramChannel(-1001000000001, 'first_channel');
  332. $first = $this->service->save(['id' => $first['id'], 'chatId' => $first['chatId'], 'bot_id' => null]);
  333. $this->assertNull($first['bot_id']);
  334. $this->service->delete($second['id']);
  335. $this->service->deleteBot($bot['id']);
  336. $this->assertSame([], $this->service->bots());
  337. }
  338. public function test_migration_preserves_shared_channel_bot_and_chooses_the_latest_token(): void
  339. {
  340. $this->migrate();
  341. $migration = require database_path('migrations/2026_11_13_150300_create_telegram_bots.php');
  342. $migration->down();
  343. foreach (['old', 'new'] as $index => $suffix) {
  344. DB::table('telegram_channels')->insert([
  345. 'name' => $suffix, 'target' => '@channel_' . $suffix, 'enabled' => true, 'message' => 'null',
  346. 'bot_username' => 'shared_bot', 'bot_name' => '机器人',
  347. 'bot_token' => Crypt::encryptString('111:fixture_' . $suffix),
  348. 'updated_at' => now()->addMinutes($index),
  349. ]);
  350. }
  351. $migration->up();
  352. $migration->up();
  353. $this->assertCount(1, $this->service->bots());
  354. $this->assertSame('111:fixture_new', Crypt::decryptString(DB::table('telegram_bots')->value('bot_token')));
  355. $this->assertCount(1, DB::table('telegram_channels')->distinct()->pluck('bot_id'));
  356. $this->assertSame(0, DB::table('telegram_channels')->whereNotNull('bot_token')->count());
  357. }
  358. public function test_wrong_bot_username_does_not_replace_existing_token(): void
  359. {
  360. $this->migrate();
  361. $this->telegramResult(['id' => 111, 'is_bot' => true, 'username' => 'first_bot', 'first_name' => '机器人一']);
  362. $this->telegramChannel(-1001000000001, 'first_channel');
  363. $first = $this->service->save($this->message('@first_channel', '一') + ['bot_token' => '111:fixture_first']);
  364. $before = DB::table('telegram_bots')->where('id', $first['bot_id'])->value('bot_token');
  365. $this->telegramResult(['id' => 222, 'is_bot' => true, 'username' => 'second_bot', 'first_name' => '机器人二']);
  366. $request = $this->request([
  367. 'id' => $first['id'], 'chatId' => $first['chatId'],
  368. 'bot_username' => 'first_bot', 'bot_token' => '222:fixture_second',
  369. ]);
  370. $result = (new TelegramChannel())->save($request, $this->service)->getData(true);
  371. $this->assertSame(-3, $result['code']);
  372. $this->assertStringContainsString('不匹配', $result['msg']);
  373. $this->assertStringNotContainsString('222:fixture_second', $result['msg']);
  374. $this->assertSame($before, DB::table('telegram_bots')->where('id', $first['bot_id'])->value('bot_token'));
  375. }
  376. public function test_publish_permission_is_independent_from_save_permission(): void
  377. {
  378. $this->migrate();
  379. $this->installPermissions();
  380. DB::table('roles')->insert(['id' => 9]);
  381. DB::table('role_user')->insert(['user_id' => 2, 'role_id' => 9]);
  382. $saveButton = DB::table('menus')->where('uri', TelegramChannelService::MANAGE)->value('id');
  383. DB::table('role_menu')->insert(['menu_id' => $saveButton, 'role_id' => 9]);
  384. $request = $this->request(userId: 2);
  385. $middleware = new CheckButtonPermission();
  386. $save = (new Route('POST', TelegramChannelService::MANAGE, fn () => null))->defaults('require_active_button', true);
  387. $request->setRouteResolver(fn () => $save);
  388. $this->assertTrue($middleware->handle($request, fn () => true));
  389. $publish = (new Route('POST', TelegramChannelService::PUBLISH, fn () => null))->defaults('require_active_button', true);
  390. $request->setRouteResolver(fn () => $publish);
  391. $this->assertSame(-1, $middleware->handle($request, fn () => true)->getData(true)['code']);
  392. $this->assertSame([], $this->requests);
  393. }
  394. public function test_external_media_url_is_passed_to_telegram_without_downloading_it(): void
  395. {
  396. $this->migrate();
  397. $this->app->register(FilesystemServiceProvider::class);
  398. $this->telegramChannel(-1001000000001, 'first_channel');
  399. $media = 'https://files.example.test/photo.jpg';
  400. $channel = $this->service->save(['chatId' => '@first_channel', 'type' => 'image', 'image' => $media]);
  401. $this->telegramResult(['message_id' => 18]);
  402. $this->assertTrue($this->service->publish($channel['id'], false)['sent']);
  403. $this->assertStringEndsWith('/sendPhoto', $this->requests[1]['request']->getUri()->getPath());
  404. parse_str((string) $this->requests[1]['request']->getBody(), $sent);
  405. $this->assertSame($media, $sent['photo']);
  406. }
  407. public function test_admin_upload_is_sent_as_a_file_and_migration_can_be_retried(): void
  408. {
  409. $this->migrate();
  410. $this->app->register(FilesystemServiceProvider::class);
  411. $disk = Storage::disk('public');
  412. $file = 'videos/' . bin2hex(random_bytes(16)) . '.mp4';
  413. $disk->put($file, 'test video');
  414. try {
  415. $this->telegramChannel(-1001000000001, 'first_channel');
  416. $channel = $this->service->save([
  417. 'chatId' => '@first_channel', 'type' => 'video', 'video' => $disk->url($file),
  418. ]);
  419. $this->service->setDefault($channel['id']);
  420. (require database_path('migrations/2026_11_13_150000_create_telegram_channels.php'))->up();
  421. $this->assertTrue($this->service->detail($channel['id'])['is_default']);
  422. $this->telegram->append(function ($request) {
  423. $this->assertStringEndsWith('/sendVideo', $request->getUri()->getPath());
  424. $this->assertStringStartsWith('multipart/form-data;', $request->getHeaderLine('Content-Type'));
  425. $this->assertStringContainsString('test video', (string) $request->getBody());
  426. return new Response(200, [], '{"ok":true,"result":{"message_id":18}}');
  427. });
  428. $this->assertTrue($this->service->publish($channel['id'], false)['sent']);
  429. } finally {
  430. $disk->delete($file);
  431. }
  432. }
  433. }
  434. class TelegramChannelTestRequest extends Request
  435. {
  436. public object $user;
  437. }