TelegramChannelMessageService.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. <?php
  2. namespace App\Services;
  3. use Carbon\CarbonImmutable;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Validation\ValidationException;
  7. class TelegramChannelMessageService
  8. {
  9. private const TABLE = 'telegram_channel_messages';
  10. public function __construct(private TelegramChannelService $channels) {}
  11. public function list(int $page): array
  12. {
  13. $items = DB::table(self::TABLE)->orderByDesc('id')->paginate(20, ['*'], 'page', $page);
  14. return ['list' => array_map($this->present(...), $items->items()), 'total' => $items->total()];
  15. }
  16. public function create(array $input): array
  17. {
  18. return $this->createMessage($input);
  19. }
  20. public function resend(int $id): array
  21. {
  22. $original = DB::table(self::TABLE)->find($id);
  23. if ($original === null || !in_array($original->status, ['sent', 'failed', 'unknown', 'cancelled'], true)) {
  24. throw ValidationException::withMessages(['id' => '该记录无法重新发送']);
  25. }
  26. return $this->createMessage([
  27. 'channel_id' => $original->channel_id,
  28. 'is_top' => (bool) $original->is_top,
  29. ] + json_decode($original->message, true, 512, JSON_THROW_ON_ERROR), $original->target);
  30. }
  31. private function createMessage(array $input, ?string $originalTarget = null): array
  32. {
  33. $fields = Validator::make($input, [
  34. 'channel_id' => 'required|integer|min:1',
  35. 'scheduled_at' => 'nullable|date_format:Y-m-d\TH:i:sP',
  36. 'is_top' => 'sometimes|boolean',
  37. ])->validate();
  38. $message = TelegramChannelService::message($input);
  39. $channel = $this->channels->detail((int) $fields['channel_id']);
  40. $target = $channel['telegram_chat_id'] ?? $channel['chatId'];
  41. if ($originalTarget !== null && $target !== $originalTarget) {
  42. throw ValidationException::withMessages(['channel_id' => '频道标识已变更,请重新创建发送记录']);
  43. }
  44. if (!$channel['enabled']) {
  45. throw ValidationException::withMessages(['channel_id' => '请先启用频道']);
  46. }
  47. if ($channel['bot_id'] === null) {
  48. throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
  49. }
  50. $scheduled = isset($fields['scheduled_at']) ? CarbonImmutable::parse($fields['scheduled_at'])->utc() : null;
  51. if ($scheduled !== null && $scheduled->lessThanOrEqualTo(now('UTC'))) {
  52. throw ValidationException::withMessages(['scheduled_at' => '定时发送时间必须晚于当前时间']);
  53. }
  54. $id = (int) DB::table(self::TABLE)->insertGetId([
  55. 'channel_id' => $channel['id'],
  56. 'channel_name' => $channel['name'],
  57. 'target' => $target,
  58. 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  59. 'is_top' => $fields['is_top'] ?? false,
  60. 'status' => 'scheduled',
  61. 'scheduled_at' => $scheduled ?? now('UTC'),
  62. 'created_at' => now('UTC'),
  63. 'updated_at' => now('UTC'),
  64. ]);
  65. if ($scheduled === null) {
  66. $this->dispatch($id);
  67. }
  68. return $this->present(DB::table(self::TABLE)->find($id));
  69. }
  70. public function cancel(int $id): void
  71. {
  72. if (!DB::table(self::TABLE)->where('id', $id)->where('status', 'scheduled')->update([
  73. 'status' => 'cancelled',
  74. 'updated_at' => now('UTC'),
  75. ])) {
  76. throw ValidationException::withMessages(['id' => '只有待发送消息可以取消']);
  77. }
  78. }
  79. public function dispatchDue(): void
  80. {
  81. DB::table(self::TABLE)->where('status', 'sending')
  82. ->where('attempted_at', '<=', now('UTC')->subMinutes(10))->update([
  83. 'status' => 'unknown', 'error' => '发送中断,结果未知,请到频道核对', 'updated_at' => now('UTC'),
  84. ]);
  85. $ids = DB::table(self::TABLE)->where('status', 'scheduled')
  86. ->where('scheduled_at', '<=', now('UTC'))->orderBy('scheduled_at')->orderBy('id')->limit(20)->pluck('id');
  87. foreach ($ids as $id) {
  88. $this->dispatch((int) $id);
  89. }
  90. }
  91. private function dispatch(int $id): void
  92. {
  93. $claimed = DB::table(self::TABLE)->where('id', $id)->where('status', 'scheduled')
  94. ->where('scheduled_at', '<=', now('UTC'))->update([
  95. 'status' => 'sending', 'attempted_at' => now('UTC'), 'updated_at' => now('UTC'),
  96. ]);
  97. if (!$claimed) {
  98. return;
  99. }
  100. $row = DB::table(self::TABLE)->find($id);
  101. try {
  102. $result = $this->channels->publishMessage(
  103. (int) $row->channel_id,
  104. json_decode($row->message, true, 512, JSON_THROW_ON_ERROR),
  105. (bool) $row->is_top,
  106. $row->target,
  107. );
  108. } catch (ValidationException $e) {
  109. $result = ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => $e->validator->errors()->first()];
  110. }
  111. DB::table(self::TABLE)->where('id', $id)->where('status', 'sending')->update([
  112. 'status' => match ($result['sent']) { true => 'sent', false => 'failed', null => 'unknown' },
  113. 'telegram_message_id' => $result['message_id'],
  114. 'pinned' => $result['pinned'],
  115. 'error' => $result['error'],
  116. 'updated_at' => now('UTC'),
  117. ]);
  118. }
  119. private function present(object $row): array
  120. {
  121. $data = (array) $row;
  122. $data['message'] = json_decode($row->message, true);
  123. $data['is_top'] = (bool) $row->is_top;
  124. $data['pinned'] = $row->pinned === null ? null : (bool) $row->pinned;
  125. foreach (['scheduled_at', 'attempted_at', 'created_at', 'updated_at'] as $key) {
  126. $data[$key] = $row->$key === null ? null : CarbonImmutable::parse($row->$key, 'UTC')->toIso8601String();
  127. }
  128. return $data;
  129. }
  130. }